简体   繁体   中英

Exporting image in runnable jar doesn't work

I'm having a weird problem in java. I want to create a runnable jar: This is my only class:

public class Launcher {

public Launcher() {
    // TODO Auto-generated constructor stub
}

public static void main(String[] args) {
    String path = Launcher.class.getResource("/1.png").getFile();
    File f = new File(path);
    JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));

}

}

As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)

As soon as I export the project to a runnable jar and launch it, it returns false. I don't know why. Somebody has an idea? Thanks in advance

edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images

If you would like to load resources from your .jar file use getClass().getResource() . That returns a URL with correct path.

Image icon = ImageIO.read(getClass().getResource("image´s path"));

To access images in a jar, use Class.getResource() .

I typically do something like this:

InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
   throw new RuntimeException("Icon.png not found.");
}

try {
   return ImageIO.read(stream);
} catch (IOException e) {
   throw new RuntimeException(e);
} finally {
   try {
      stream.close();
   } catch(IOException e) { }
}

Still you're understand, Kindly go through this link.

Eclipse exported Runnable JAR not showing images

Because the image is not separate file but packed inside the .jar.

Use the code to create the image from stream

InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);

尝试使用它来获取图像

InputStream input = getClass().getResourceAsStream("/your image path in jar");

Two Simple steps:

1 - Add the folder ( where the image is ) to Build Path;

2 - Use this:

InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM