Reputation: 9692
I have resources in my java project under resources folder. When i use following ways [2] to load the resource it is working . But when i deploy my war in wildfly 9.x it says cannot find the file.avsc file. It gives the class path as[1]; How can i load resource files in jboss war?
[1]
java.io.FileNotFoundException: /content/ratha.war/WEB-INF/lib/core-0.0.1-SNAPSHOT.jar/avro_schemas/file.avsc (No such file or directory)
[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());
Upvotes: 2
Views: 9165
Reputation: 17075
The accepted answer didn't work for me on both JBoss and Tomcat. Because of the classloader hierarchy, it looks like the safest option is to use current thread's classloader as nicely described here:
https://coderanch.com/t/89900/application-servers/reading-properties-file
What it looks like in code:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("avro_schemas" + File.separator + "file.avsc");
File file = new File(resource.getFile());
Upvotes: 2
Reputation: 7867
Try the Class.getResourceAsStream()
method:
this.getClass().getResourceAsStream("avro_schemas/file.avsc");
You may have to tinker with the path a little. Here is the formal documentation on how the path should be constructed: Class.getResourceAsStream
The issue will be how Jboss creates it's ClassLoader structure. You will need to construct the path to match how the class is represented in the ClassLoader classpath.
Other good descriptions for this can be found here: How to read a file from jar in Java? and here: How can I read a resource file in an unexploded war file deployed in Tomcat?
Where it suggests you should have a leading "/" to start the path to the file.
Upvotes: 3