Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a resource from a java library packed into its own .jar

Tags:

java

file

maven

jar

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.

like image 439
Alex Avatar asked Jul 06 '17 14:07

Alex


2 Answers

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.

like image 105
Hiran Perera Avatar answered Oct 18 '22 02:10

Hiran Perera


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.

like image 4
Alex Avatar answered Oct 18 '22 04:10

Alex