Reputation: 4767
I'm making a game in Java. I load the level map processing a text file. The textfile is inside workspace/src/resources/sprites/misc/level.txt. When I compile the game from Eclipse it works perfectly, 0 problems. When I export the game into a JAR file or a Runnable JAR file, if I open the .jar the game window opens and the game starts but the whole level is missing, and the main character falls to Limbo. The same problem happens if, inside the source code, I put a wrong file path. So I'm 100% the problem is that when I make the JAR file, for some reason it messes up the text file's path. It's weird because it doesn't happen with the player's sprites! I can see it but I can't see the level.
Also, I load the sprites like this:
currentSprite = new Sprite(new ImageIcon(getClass().getClassLoader().getResource("sprites/background/pricebox.gif")));
And process the text file like this:
File f = new File("resources/sprites/misc/level.txt");
BufferedReader in = new BufferedReader(new FileReader(f));
What could be the problem?
Thank you.
Upvotes: 0
Views: 3123
Reputation: 2635
Maybe this will help you
http://www.javaworld.com/javaworld/javatips/jw-javatip49.html
Also please see File separator for specifying file separator slashes.
Upvotes: 0
Reputation: 128919
A File represents a file on the file system. When it's inside a JAR, it's not a file on the file system. You want to load your resource in the same way you load your image--as a class path resource:
BufferedReader in = new BufferedReader(
new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"resources/sprites/misc/level.txt")));
or slightly more roundabout, but more similar to how you're loading the image:
URL resource = getClass().getClassLoader().getResource(
"resources/sprites/misc/level.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(resource.openStream()));
Upvotes: 3