Kieran Jones
Kieran Jones

Reputation: 1

Java using an image inside a .jar file

I know questions like this have been asked before, but I have looked and tried a lot of the answers and none of them work. I am trying to use an image inside a .jar file. The image is stored in the directory /world/maps/map1.jpg.

            BufferedImage bigImg;
            try
            {
                bigImg = ImageIO.read(getClass().getResourceAsStream("/world/maps/" + name + ".jpg"));
            }
            catch(Exception e)
            {
                System.out.println(e + ": is the error");
                bigImg = null;
            }

Thanks for the help.

forgot to make it clear but class file is in the same directory as image

Upvotes: 0

Views: 1652

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

The class on which getClass() is called must reside in the same jar. And the path must be case sensitive. Are you sure that name is "image"?

Upvotes: 0

elias
elias

Reputation: 15480

If you directory tree is something like:

SomeClass.class
world
|--maps
   |--image.jpg

You can use some reference like:

SomeClass.class.getResource("./world/maps/image.jpg")

If the class is inside some another directory, just add ../ to the path.

Upvotes: 1

Related Questions