1

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)

user19955
  • 75
  • 1
  • 5
  • 1
    Possible duplicate of [How to access resources in JAR file?](http://stackoverflow.com/questions/2393194/how-to-access-resources-in-jar-file) – Jérôme Mar 10 '17 at 22:54
  • Objects in a jar are not files and you can't use `File` to access them. – greg-449 Mar 11 '17 at 08:10

2 Answers2

4

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"))
Alon Segal
  • 818
  • 9
  • 20
  • I tried it seems to work, but a scanner i am using is giving me problems `Scanner s = new Scanner(this.getClass().getClassLoader().getResourceAsStream("levels/"+fileName)); ` This doesnt seem to work properly when packaged. – user19955 Mar 10 '17 at 23:45
  • @user19955 If you're trying to read the file than you should not be using Scanner, try that solution instead: http://stackoverflow.com/questions/29611661/how-to-make-scanner-strings-into-a-stream-in-java – Alon Segal Mar 10 '17 at 23:51
3

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.

Sheinbergon
  • 2,875
  • 1
  • 15
  • 26