Search code examples
javaimagebuildjarembedded-resource

Java images loaded in ide but not built jar


I have my file path as follows:

  +------------+           +-----------------+      +------------------+
  |            |           |                 |      |                  |
  | src        +----------->  com            +--+--->  application     |
  |            |           |                 |  |   |                  |
  +------------+           +-----------------+  |   +------------------+
                                                |
                                                |   +------------------+
                                                |   |                  |
                                                +--->  resources       |
                                                    |                  |
                                                    +------------------+

My code is in the application folder and my pictures that I want to load are in resources.

Im using the following code to get the images from resources onto a class in application (image is a BufferedImage).

image = ImageIO.read(new File("./src/com/resources/Pad.png"));

This seems to work in my IDE (intellij) as I can see the loaded images as shown

However, when I build, the images aren't being shown. I'm building by:

File -> Project Structure -> Artifacts -> Green plus -> JAR -> From modules with dependencies -> my main class location -> Extract to target Jar

Then I Build Artifact -> Build.

So when I go to the destination of the built jar and run it none of the pictures are being shown

I checked to see if the images were in the built jar by extracting the jar which does contain the pictures but for some reason the code isn't loading the picture.


Solution

  • You can try to use resourse as a stream instead of file.

    image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("com/resources/Pad.png"))