如何在jboss war - wildfly9.xV中加载资源文件

How to load resource files in jboss war - wildfly9.xV

我的 java 项目资源文件夹下有资源。当我使用以下方式 [2] 加载它正在工作的资源时。但是当我在 wildfly 9.x 中部署我的 war 时,它说找不到 file.avsc 文件。 它将 class 路径指定为 [1];如何在 jboss war 中加载资源文件?

[1]

java.io.FileNotFoundException: /content/ratha.war/WEB-INF/lib/core-0.0.1-SNAPSHOT.jar/avro_schemas/file.avsc(没有那个文件或目录)

[2]

ClassLoader classLoader = getClass().getClassLoader();

   ClassLoader classLoader = this.getClass().getClassLoader();

   ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

   File file = new File(classLoader.getResource("avro_schemas/file.avsc").getFile());

试试Class.getResourceAsStream()方法:

this.getClass().getResourceAsStream("avro_schemas/file.avsc");

您可能需要稍微修改路径。以下是关于如何构建路径的正式文档:Class.getResourceAsStream

问题在于 Jboss 如何创建它的 ClassLoader 结构。您将需要构造路径以匹配 class 在 ClassLoader class 路径中的表示方式。

可以在此处找到其他很好的描述:How to read a file from jar in Java? 在这里:How can I read a resource file in an unexploded war file deployed in Tomcat?

它建议您使用前导“/”作为文件路径的开始。

接受的答案在 JBoss 和 Tomcat 上都不适合我。由于类加载器层次结构,看起来最安全的选择是使用当前线程的类加载器,如下所述:

https://coderanch.com/t/89900/application-servers/reading-properties-file

它在代码中的样子:

 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 URL resource = classLoader.getResource("avro_schemas" + File.separator + "file.avsc");
 File file = new File(resource.getFile());