Skip to content

Loading images/files inside jar

There are already heaps of answers to this problem. I have also tried a lot of them. I have not found a solution yet.

I load some images within my project (Swing – ImageIcons). In the run dialog all of them are also displayed in my GUI. But after compiling the program can’t be started at all. The error messages are different depending on the procedure.

Lastly, I tried simply loading a File to print the absolute path. This then looked like this:

File f = new File(Loadscreen.class.getResource("../../../../resources/materials/icon.png").getFile());

The console returns a NullPointerException for this:

Console compiled:

Exception in thread "main" java.lang.NullPointerException
        at de.franken.ration.gui.Loadscreen.<init>(
        at de.franken.ration.Rationboard.onEnable(
        at de.franken.ration.Rationboard.main(

Console Eclipse:


In line 43 I define f.

My tree looks like this:

L_ src
  L_ de
    L_ franken
      L_ ration
        L_ gui
          L_ Loadscreen.class
  L_ resources
    L_ materials
      L_ icon.png

However, the icon is included in the JAR.

Thanks to all who respond.

//EDIT: I played around a bit more. As long as the resource to be loaded is in the same package, it can be loaded. But if I change the package with ../, the NullPointerException comes up.




Note the two differences to the approach seen in the question:

  1. this.getClass() will find the context class loader appropriate for application resources.
  2. "/resources/materials/icon.png" the leading / will tell the getResource method to search from the root of the class-path or Jar.

BTW: Don’t get files involved at any point. getResource returns an URL and resources in a Jar are not accessible as File objects.