Home > Enterprise >  Loading images/files inside jar
Loading images/files inside jar

Time:03-16

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());
System.out.println(f.getAbsolutePath());

The console returns a NullPointerException for this:

Console compiled:

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

Console Eclipse:

H:\Users\Hinrich\Documents\Java\Rationboard\bin\resources\materials\icon.png

In line 43 I define f.

My tree looks like this:

Rationsboard
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.

CodePudding user response:

You can verify, as a first step, that the icon is included within the jar, by running jar -tf file.jar.

Have you tried

File f = new File(Loadscreen.class.getResource("/materials/icon.png").getFile()); System.out.println(f.getAbsolutePath());

assuming that the icon.png is in resources/materials folder?

CodePudding user response:

Use:

this.getClass().getResource("/resources/materials/icon.png"); 

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.

  • Related