Load Image from Jar: Always null

2019-01-18 15:54发布

问题:

Looked at other posts on SO and they did not solve this issue.

I'm trying to load an image from my jar file. It is continuously coming up as null. The image is located under:

.Jar file > images > BLOCK.png

To load the image I am doing:

BufferedImage bImg;
URL url = getClass().getResource("/images/BLOCK.png");
try {
    bImg = ImageIO.read(url);
} catch (IOException ex) {
    Logger.getLogger(TileEngine.class.getName()).log(Level.SEVERE, null, ex);
}

url is null as is bImg.

Do not worry about case sensitivity as I've already checked that.

回答1:

try this :

Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/BLOCK.png"));


回答2:

Which jar file is the image in, compared with the class you're using to call getResource? If they're loaded by the same classloader, it should be fine.

Have you double-checked that the jar file actually contains the file?

Are you sure that your classloader is actually using the jar file at all (rather than .class files directly on disk, for example)?

If you have a short but complete program which demonstrates the problem, that would really help. (A console app would be ideal... we don't need to see the image, after all.)



标签: java image null