How to access resources in JAR file?

I see two problems with your code:

getClass().getResourceAsStream(imgLocation);

This assumes that the image file is in the same folder as the .class file of the class this code is from, not in a separate resources folder. Try this instead:

getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation);

Another problem:

byte abyte0[] = new byte[imageStream.available()];

The method InputStream.available() does not return the total number of bytes in the stream! It returns the number of bytes available without blocking, which is often much less.

You have to write a loop to copy the bytes to a temporary ByteArrayOutputStream until the end of the stream is reached. Alternatively, use getResource() and the createImage() method that takes an URL parameter.

Leave a Comment