I have a library project with some resources that I would like to load and use. I would be using this library in another project so I have to pack the resources into the .jar. This is how that's achieved:
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
The problem comes when trying to retrieve the file, I do:
String resourceName = "myTemplateResource.json";
URL url = MyClass.class.getClassLoader().getResource(resourceName);
url is assigned a null
value. It happens in the library's tests and in the dependant project. Any hint of what is missing?
Also tested using
MyClass.class.getResource("/myTemplateResourceName.json");
and
MyClass.class.getClassLoader().getResource("src/main/resources/myTemplateResource.json");
with the same result.
Use getResourceAsStream()
method to load the resource from the .jar file as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(locaiton);
e.g.: If the file 'myTemplateResourceName.json' is located directly in the resources folder, use only the file name. It is wrong if you add a slash (/) in front of the path.
InputStream inputStream = classLoader.getResourceAsStream("myTemplateResourceName.json");
Note: You have to place the resource file in the main/resources
(don't keep it in the test/resources
section since that is not packed in the jar file) folder in the project which is being used to create the jar file.
There was something wrong with the filename that I was not able to find out. Renamed the file and now it's fine.
To answer my question:
First add the resource to the jar on the .pom file.
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
Then access your file.
URL url = MyClass.class.getClassLoader().getResource(resourceName);
From there you can get an InputStream
. As simple as it looks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With