javajavax.imageioresource-loading

.jar will not find internal resource images but compiled program does


I've been trying to load some pictures to use in my Swing UI and while my compiled program will load the images correctly, my .jar does not find the images.

First of all, I've marked my resource file as "Resource Root". The project layout looks like this:

project layout shown.Outside of the source folder, there is the resource folder, and inside it an images folder with the resources in question.

The compilation output layout looks like this:

enter image description here

The .jar layout looks like this:

enter image description here

Now, the code that's been loading the pictures is inside the gui package; here it is:

        try {
            System.out.println(this.getClass().getResource("../images/buttonClip.png").getPath());
            attchmntBtnImg = ImageIO.read(getClass().getResource("../images/buttonClip.png"));
            sendMsgBtnImg  = ImageIO.read(getClass().getResource("../images/buttonForward.png"));
        }
        catch (IOException e) {
            e.printStackTrace();
        }

The print line output prints correctly the path of the picture

/C:/Users/path/to/Project/out/production/Peer2Party_desktop/images/buttonClip.png

While there are no errors when running it from intellij idea, the artifact generated (if I run it from the cmd, with or without administrator priviledges) gives me a NullPointerException at the System.out.println(), but, undoubtedly, that's not the cause of the error, since it'll still crash on the next line even if I remove the println.

enter image description here

I've tried to do these in order to load the images, to no avail:

this.getClass().getResource("/../images/buttonClip.png");
getClass().getResource("/../images/buttonClip.png");
this.getClass().getResource("images/buttonClip.png");
getClass().getResource("images/buttonClip.png");
this.getClass().getResourceAsStream("images/buttonClip.png");
getClass().getResourceAsStream("images/buttonClip.png");

Any help is very VERY welcome.

Important note: I'm on windows 10, the pictures are inside the correct path(file.jar/images/buttonClip.png), but at runtime the .class won't find it


Solution

  • Simply use

    this.getClass().getResource("/images/buttonclip.png");
    

    it looks for the file from project root directory