Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JAR resources

I have a jar file with resources (mainly configuration for caches, logging, etc) that I want to distribute.

I'm having a problem with the relative paths for those resources, so I did what I've found in another stackoverflow question, which said that this was a valid way:

ClassInTheSamePackageOfTheResource.class.getResourceAsStream('resource.xml');

Sadly this does not work.

Any ideas? Thanks!

PS: Obviously I cannot use absolute paths, and I'd like to avoid environment variables if possible

like image 879
Pablo Fernandez Avatar asked Apr 14 '10 18:04

Pablo Fernandez


People also ask

How do I access a JAR file?

How To Open JAR Files. If you want to view each file in a non-executable jar file, you can do that with the help of a JAR file compatible compression/decompression software. Either WinRAR or 7-ZIP, any one of them is a good choice. After you have installed WinRAR or 7-ZIP, run it, open the file, and extract files in it ...

Do jar files contain resources?

jar ) contain your executable classes and resource files. A jar can also contain other jar files, which is useful when your program needs some library which is packaged in a jar.

How do we access resources in Java code?

Java programs can use two mechanisms to access resources: Applets use Applet. getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet. getAudioClip(url) .

Can you get source code from a JAR file?

Jar files are archive files that contains of a lot of different java classes (files). You can use winzip/winrar to open the jar files and you can see those java classes in jar files. Typically you can use a Java decompiler to decompile the class file and look into the source code.


2 Answers

Make sure that your resource folder is listed as a source folder in your project settings. Also, make sure that the resource folder is set to export when you build your jar.

You can add a .zip extension to your jar file then open it up to ensure that your resources are included and at the expected location.

I always use absolute paths like this:

InputStream input = this.getClass().getResourceAsStream("/image.gif");

When you use absolute paths, "/" is the root folder in the jar file, not the root folder of the host machine.

like image 188
Marcus Adams Avatar answered Sep 23 '22 06:09

Marcus Adams


I always have to puzzle through getResourceAsStream to make this work. If "resource.xml" is in org/pablo/opus, I think you want this:

Name.class.getResourceAsStream("org.pablo.opus.resource.xml");
like image 22
trashgod Avatar answered Sep 23 '22 06:09

trashgod