简体   繁体   中英

How to add path to resource directory to an executable jar

I am trying to create an executable jar (code.jar) that depends on another jar file (other.jar) that I create in a separate project(=directory).

The problem I'm having is that there is a class in other.jar that looks for an image file (xyz.gif) that is contained within that project: eg, project 'other' looks like: build/ images/xyz.gif src/... etc.

I make other.jar (including the /images directory) and then I make code.jar.

However, when I run java -jar code.jar - it is unable to locate xyz.gif: java.lang.IllegalArgumentException: input == null! at javax.imageio.ImageIO.read(ImageIO.java...)

I have tried everything I can think of to communicate the path to images/xyz.gif to the jar, including: 1. I tried adding the CLASS-PATH: images/ to the MANIFEST.MF for other.jar 2. I tried copying the images directory into the build for code.jar and adding CLASS-PATH: images/ to the MANIFEST.MF for code.jar 3. I tried putting CLASS-PATH: images/xyz.gif - in both manifest files

This seems like a general problem: How to include a (non-class) resource (eg, an image file) to a java jar file in such a way that java can locate it (without subsequent packages that utilize the sub-package - eg, code.jar uses other.jar) needing to know the details.

Say I can successfullly run the code project using:

java -cp somepath/images com.xyz.code

What I want to do is run:

java -jar code.jar - and have it locate the images/ directory on the classpath.

I should add that the image-containing jar (other.jar) project is not my code - I am just trying to compile it to use. That code tries to load the image using: javax.imageio.ImageIO.read(ClassLoader.getSystemResource("xyz.gif"); There seems to be a lot of discussion about whether this is the correct/best way to load an image - I assume that the authors of this code DID have it working using Eclipse (whi ch likely sorted out the paths), and I simply want to get it working on the command line (and eventually in ant).

Any help would be greatly appreciated. I don't understand why the documentation on jar creation is so minimal.

Instead of running jar directly try putting it in classpath. Something like this:

java -cp code.jar MainClass

This might work.

EDIT:

Above solution will not work. Try the below code to get image.

ImageIcon myIcon = new ImageIcon( this.getClass().getResource("/resources/icon.gif"));

and place the image at below locations:

/myApp/src/resources/icon.gif
/myApp/bin/resources/icon.gif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM