1

I just started a new game project and I want to create the world by reading a file.

In Eclipse everything is just fine and the file is successfully loaded. The images that are used are being loaded as well.

But if I compile the project and execute the .jar the images still work but the file could not be found.

I loaded the image by using the classpath:

ImageIO.read(SpriteSheet.class.getResourceAsStream("..."));

and the file by using the path:

new File("...")

They are both in the same folder and I do not now why this does not work because in Eclipse everything just worked fine but after compiling it does not work anymore.

ADTC
  • 8,999
  • 5
  • 68
  • 93
  • http://stackoverflow.com/questions/7718807/can-getresourceasstream-find-files-outside-the-jar-file This might be helpful. – Mark W Jan 06 '14 at 16:44
  • Your English is very good, so I'm surprised you say `i` instead of `I` (that's the only grammar correction I made). – ADTC Jan 06 '14 at 16:45

1 Answers1

1

Assuming you're using relative paths,

When you use getResoureAsStream you can load any file in your classpath.

But when you use new File your file must reside in the current working directory or in any folder defined in the operating system's path environment variable (not necessarily your classpath).

Your Eclipse is probably able to pick up the file because it is executing your program from where the file is. You are not able to do the same because you're executing the program from elsewhere.

ADTC
  • 8,999
  • 5
  • 68
  • 93
  • And how could i get the actual File in the classpath? – user3166097 Jan 06 '14 at 16:47
  • 1
    You can't. `File` is not designed to get files in your classpath. It is designed to get any file in your hard disk. Normally you will define a full absolute path in `new File("...")` because relative paths are not guaranteed to be the same from *system to system* or from *run to run*. You can however, add the folder holding your file in the environment's `PATH` variable, and your program should be able to find it. ... To keep using relative paths, you have to ensure that you run your program from the correct working directory so that it can find the find the file through relative path. – ADTC Jan 06 '14 at 16:50
  • In contrast, `getResourceAsStream` is designed to get files stored inside your jar files (`File` can't do this), and that is why you are able to load resources in your classpath using this. You normally use this to load resources that you are bundling with the program, as opposed to files saved by users outside your program (for which you will use `File`) These two are for different kinds of file loading, and **non-interchangeable**. Do not confuse between the two. – ADTC Jan 06 '14 at 16:57