Trying to load icon from jar file

11,794

Solution 1

I've always used the system class loader, whose path is relative to the root of the JAR:

URL url = ClassLoader.getSystemClassLoader().getResource("icons/mouse.png");
Icon icon = new ImageIcon(url);

Solution 2

Skip the class loader, and get the resource as a stream instead. If you don't need the URL you can turn them directly into BufferedImages like so. I've left the stream and exception handling as a further exercise.

InputStream stream = LoadHTMLExample.class
    .getResourceAsStream( "/icons/mouse.png" );
BufferedImage image = ImageIO.read( stream );

Questioner needs the URL which brings us back to everyone else's suggestions. The images are definitely in the jar aren't they?

Solution 3

I think that getResource gets the resource relative to the location of LoadHTMLExample.class. So your jarfile should be structured in the following way:

myjar.jar
 |
 |- ...
 |- LoadHTMLExample.class
 |- ...
 \-- icons
      |
      \- mourse.png

Also, you might be getting stream through getResourceAsStream than getting the URL.

Share:
11,794
Admin
Author by

Admin

Updated on June 17, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to load icons from a jar file. I have both tried to load it from classes within the jar file as well as classes outside the jar file.

    outside of the jarfile - returned a null exception

    java.net.URL imageURL = LoadHTMLExample.class.getClassLoader()
        .getResource("icons/mouse.png");
    

    in side of the jar file in the LoadHTMLExample

    java.net.URL imageURL = this.getClass().getClassLoader()
        .getResource("icons/mouse.png");
    

    get the same error.

    I have also tried variations of "icons", "/icons" "icons/" "/icons/mouse.png" "icons/mouse.png"

    nothing seems to work any idea

    the icon is in the jar file

    jar
     --icons --- {all the images}
    
     --com.blah.blah
    
  • skaffman
    skaffman almost 15 years
    Class.getResourceAsStream() just delegates to the ClassLoader. It's essentially the same thing.
  • Admin
    Admin almost 15 years
    I need the URL, a webrenderobject is going to use the resource location to pull the icons
  • Dan Gravell
    Dan Gravell almost 15 years
    Everything else considered, you definitely need to do what Peter suggested, because to load "icons/mouse.png" means to load it relative to the class. In your JAR you have icons off the root, so you must prefix with a foreslash.
  • Admin
    Admin almost 15 years
    also tried you method, and image keeps is always null, so either way isn't working...what is blocking the reading of a jar file?
  • Admin
    Admin almost 15 years
    I got it to work! final java.net.URL imageURL3 = com.java.html.LoadHTMLExample.class.getResource( "icons/" ); that works for the above diagram