Search code examples
javawildflyinputstreamear

How to read the bytes of an image resource located inside a nested JAR?


I am struggling while trying to read the bytes of a PNG image bundled with the resources of a JAR. The file is located in the src/main/resources directory.

Here is my code so far:

byte[] bytes = {};
final InputStream defaultImageStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/defaultLogo.png");
new DataInputStream(defaultImageStream).readFully(bytes);

The code is executed on a Wildfly 12 server, located in a JAR included in the EAR as an EJB.

It seems than instead of retrieving the resource I asked for, getResourceAsStream returns the enclosing jar:

enter image description here

How can I get that image?

Additional info:

  • I tried both with an exploded and non-epxloded JAR in the EAR. Same results.
  • The path to the resource seems correct. Prefixing it by "/resources" ends in the method returning NULL.
  • I tried using the Class' classloader instead of the thread context's one. Same results.
  • I envisioned going through all the entries of the enclosed JAR myself, but this both seems overkill and difficult: since I have a JarInputStream and no JarFile, how would I read the data corresponding to an entry?

Solution

  • I think your code is working as intended. Looking at the DataInputStream instance isn't going to tell you much. Look at the content, I think it is the image you want.