StephenHynes
StephenHynes

Reputation: 53

Exporting an JAR file in Eclipse and referencing a file

I have a project with a image stored as a logo that I wish to use.

URL logoPath = new MainApplication().getClass().getClassLoader().getResource("img/logo.jpg");

Using that method I get the URL for the file and convert it to string. I then have to substring that by 5 to get rid of this output "file:/C:/Users/Stephen/git/ILLA/PoC/bin/img/logo.jpg"

However when I export this as a jar and run it I run into trouble. The URL now reads /ILLA.jar!/ and my image is just blank. I have a gut feeling that it's tripping me up so how do I fix this?

Cheers

Upvotes: 1

Views: 1002

Answers (2)

JasonG
JasonG

Reputation: 5962

See here: Create a file object from a resource path to an image in a jar file

String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));

Note it looks like you need to use a stream for a resource inside an archive.

Upvotes: 1

Vijay Agrawal
Vijay Agrawal

Reputation: 3821

You are almost there.

Images in a jar are treated as resources. You need to refer to them using the classpath Just use getClass().getResource: something like:

getClass().getResource("/images/logo.jpg")); where "images" is a package inside the jar file, with the path as above

see the leading / in the call - this will help accessing the path correctly (using absolute instead of relative). Just make sure the path is correct

Also see:

How to includes all images in jar file using eclipse

Upvotes: 1

Related Questions