简体   繁体   中英

Java getResource not working in a .jar file

i am trying to export a pacman game i made from eclipse to a .jar package. The problem is that while everything runs fine on eclipse, when the .jar is exported, the resources i use dont load properly. I have them in a separate /res folder , which is on the build path. I access them in the following ways:

ClassLoader classLoader = getClass().getClassLoader();
    try{
         image = ImageIO.read(new File(classLoader.getResource("images/PM0.gif").getFile()));
    }
    catch (IOException e1) {
        e1.printStackTrace();

    }

File file = new File(classLoader.getResource("levels/"+fileName).getFile());

What am i doing wrong? here is an example of the errors i get(only in the exported .jar on eclipse it runs fine)

In order to retrieve resources from placed inside a jar, you need to use getResourceAsStream() .

It works on eclipse because the runtime environment is executed using the "unpacked" JAR ( or better put - prepacked ) using actual files.

When working with resources, you should always have them as streams and not as files (unless you're trying to do something really weird).

try the following:

ImageIO.read(classLoader.getResourceAsStream("images/PM0.gif"))

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