0

I am using eclipse and I use the following code to load my image from a folder.

getClass().getResource("/images/image.jpg").getFile())

The image folder is located inside the bin folder in the project folder. It works fine when loading in eclipse, but when I export it to a jar it does not load. I have tried puting the image folder in all possible places in the jar, but it does not.

How do I load an image folder in a jar?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Coupon22
  • 395
  • 8
  • 24

2 Answers2

2

You can use getResourceAsStream() method instead to get InputStream instance with your file data.

UPDATE: Loading of files from a jar happens with the help of class loader. And it can give you instance of InputStream (not FileInputStream) of any internal resource (be it image file or sound file or text file). File writing shouldn't work inside jar.

Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
  • I have adapted my code and used this. The problem is it only loads images, but sound files or file writing doesn't work outside of eclipse. How do I load sound file or use FileInputStream and FileWriter? – Coupon22 Sep 15 '12 at 13:48
  • *"but sound files .. doesn't work outside of eclipse"* Use `getResource(String)` for them. The problem with `getResourceAsStream(String)` is that it returns an input stream that cannot be repositioned. – Andrew Thompson Sep 15 '12 at 22:15
1

Use this. This method doesn't return immediately.

public Image getImage(String img){
    return new ImageIcon(getClass().getResource(img)).getImage();
}

If you want to load from the root of the JAR, then

return new ImageIcon(getClass().getClassLoader().getResources(img)).getImage();
Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91