Noah Cagle
Noah Cagle

Reputation: 459

Java jar not reading files from the jar, only external folders?

When ever I make a JAR, the JAR won't read the folder inside it, only a folder in the folder the JAR is it. OK, that wasn't very descriptive. So here is a photo I edited to support.enter image description here

I hope you get the idea now. So how would I fix this? I already have res and stats part of the build path in eclipse, now what?

Code I use to read the resources:

Image player; player = new ImageIcon("res/player.png").getImage();

Upvotes: 1

Views: 280

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

When using ImageIcon and passing it a String, it expects that the parameter refers to a File.

From the JavaDocs

Creates an ImageIcon from the specified file. ... The specified String can be a file name or a file path

Files and "resources" are different things.

Instead, try using something more like...

new ImageIcon(getClass().getResource("res/player.png"));

Assuming that res/player.png resides within the jar in side the res directory.

Depending on the relationship to the class trying to load the resource and the resource's location, you may need to use

new ImageIcon(getClass().getResource("/res/player.png"));

instead...

Updated

Some recommendations, as EJP has pointed, you should be prepared for the possibility that the resource won't be found.

URL url = getClass().getResource("/res/player.png");
ImageIcon img = null;
if (url != null) {
    img = new ImageIcon(url);
}
// Deal with null result...

And you should be using ImageIO.read to read images. Apart from the fact that it supports more (and can support more into the future) image formats, it loads the image before returning and throws an IOException if the image can't be read...

URL url = getClass().getResource("/res/player.png");
ImageIcon icon = null;
if (url != null) {
    try {
        BufferedImage img = ImageIO.read(url);
        icon = new ImageIcon(img);
    } catch (IOException exp) {
        // handle the exception...
        exp.printStackTrace();
    }
}
// Deal with null result...

Upvotes: 5

Related Questions