Possible Duplicate:
How can a Java program use files inside the .jar for read and write?
I am in the process of creating a game, and I want it all to run from on runnable jar file, so all of my resources (images and text files) are going to be inside the jar file.
The problem that I'm having with this is that it is extremely difficult to deal with files inside the jar.
I am using eclipse, which can sometimes play tricks on you because it will find the files if you run it from eclipse, but if you export it won't.
I just want to know basically the proper way to dew a few things:
- I need to be able to load images (which I have working, somehow. I sort of tinkered with it and did it on accident, so I have no clue how it works)
- I need to be able to read from text files (I have this working too, again, by accident and hours of guessing.)
- I need to be able to write to text files that exist and and are in the jar. This is what is making me think I'm doing it all wrong. All I want to do is be able to save certain settings so they work on the next load, and I have no clue how to write to the file.
In eclipse (Indigo) I made a folder names "resources" and marked it as a source folder. I put all of my images and text files in there. I read in images like this:
public static Image ammo = new ImageIcon(TankMazeGame.class.getResource("ammo.png")).getImage();
I read text files like this:
InputStream is = TankMazeRunner.class.getClassLoader().getResourceAsStream("Settings.txt");
Scanner settingsReader = new Scanner(new InputStreamReader(is));
I am writing to my settings file like this, but it isn't really working, so that's what I need help with.
File settingsFile = new File(DisplayMenu.class.getClassLoader().getResource("Settings.txt").getFile());
try {
OutputStream os = new FileOutputStream(settingsFile, true);
PrintWriter pw = new PrintWriter(os, true);
pw.write("SIZE: " + TankMazeRunner.WIDTH + "\n");
os.flush();
pw.close();
} catch (Exception e2) {
System.out.println("Error");
}
As you can probably tell from my code, I'm lost.