简体   繁体   中英

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

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.

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" ?

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