Java jar problem

Started by
3 comments, last by rip-off 13 years, 5 months ago
Hi,

I'm making a game in java. The program runs perfectly in netbeans but after I make a executable jar out of it, the game opens up then crashes.

After I did some System.out.println() in various places in the program I found something very strange:

When I run the program in netbeans the program loads text files (which I use as maps for the game) from:

C:\Users\Yati\Documents\NetBeansProjects\2DGame\maps\map1.txt

But when I run the jar through cmd (so i can see the output lines) the program looks in this:

C:\Users\Yati\maps\map1.txt

What the hell?! I've been pulling my hair out on this one! How can I fix this?

P.S - I didn't put up my code since its a little big now.

P.S - Here is my file loading code:

filename is a string passed into the method

File mapFile=new File(filename);
System.out.println(mapFile.getAbsolutePath());

// read every line in the text file into the list
BufferedReader reader = new BufferedReader(new FileReader(filename));

then there is code to read the txt file and make the map but that not necessary here.



[Edited by - yati1 on October 22, 2010 6:17:27 AM]
Advertisement
The paths appear to be relative to your current working directory.

How should your code know what the path "maps\map1.txt" really means?
Sounds like you need to read up on how the java classpath works. Basically you should use paths relative to the classpath, and setup your Netbeans project and jar to set the classpath so that your relative paths map onto the files as you want them.

We could probably help you if you posted your file loading code as well. Generally you want to use getClass().getResourceAsStream() otherwise you'll have environment / compatibility issues.
Ok. From what I know java uses classpaths to look for the files to compile. So how do I specify classpath to use to get to the maps/map1.txt file? Is it something I have to program or do I have to configure Netbeans to build the jar that way?
There are three primary solutions. One is to use all absolute paths (e.g. pass the directory all your data is in via the command line or a property file). Another is to package the data as part of the JAR, and use the classloader to reference it. The former is the most flexible, but can be difficult to setup (you might need a bootstrap batch file or executable). The latter is easier, but the least flexible. In particular, if you want to encourage modding I would not go with the JAR solution. A final solution is to have a bootstrap program or batch file that sets the working directory and then executes Java.

This topic is closed to new replies.

Advertisement