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
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 ...
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.
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) .
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.
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.
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");
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