Writing/reading to/from file
I want to write several variables and their values to a file to later on be able to load them into my application for a simple save/load game feature.
I tried with FileOutputStreams and whatnot but I can't see how I can make it store several variables and their values and then load them. I was thinking something like this
publicvoid save()
{
try{
// Write objects to file
os =new FileOutputStream("t.txt");
// write aVariable w/ value to os
// write anotherVariable w/ value to os
os.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
publicvoid load()
{
try{
// Read objects from file
FileInputStream is =new FileInputStream("t.txt");
// load aVariable's value
// load anotherVariable's value
// use aVariable's value to something (i e setting aVariable to aVariable's just-loaded value
is.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
I read about storing data in arrays and stuff but I just don't understand. A simple example would be greatly appreciated.
[2235 byte] By [
Lombraa] at [2007-11-27 2:13:46]

Ok, so I managed to come up with this
public void save()
{
try {
dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("savedata.txt")));
dos.writeUTF(enemyID);
dos.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public void load()
{
try {
dis = new DataInputStream(new BufferedInputStream(new FileInputStream("savedata.txt")));
String loadEnemyID;
try {
while (true) {
loadEnemyID = dis.readUTF();
newGame.setText(loadEnemyID);
dis.close();
}
} catch (EOFException ex) { }
} catch(FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
I really had a hard time figuring out where to place all the exception catches and all, but in the end it compiled. The actual saving and loading seemed to work but when I called the load function I got an error
java.io.IOException: Stream closed
I suppose it has got something with the exception stuff to do, but what?
Thanks
> while (true) {
Why did you write an infinite loop?
This is the usual way one deals with a resource that needs to be disposed,
whether or not an error occurs -- use finally:
void method(...) throws IOException {
StreamType stream = new ...
try {
... use stream ...
} finally {
closeQuietly(stream);
}
}
void closeQuietly(Closeable stream) {
try {
stream.close();
} catch (IOException e) {
... log error? ...
}
}
You usually propagate the exception so that the caller can react to the error,
rather than sweeping it under the rug and ignoring it.