Reputation: 164
Im trying to serialize a snake game in Java, in which the game has to have the option to "save" and "load". Im not getting any error but whenever I try to print out the lifes, time, etc. It just gives me 0 when the lifes and time are not supposed to be 0.
Heres is some of my code for the saving and loading part:
public void SaveGame() throws IOException {
PnlCentro pnlCentro = new PnlCentro();
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(pnlCentro);
out.close();
}
public void LoadGame() throws FileNotFoundException, IOException, ClassNotFoundException {
PnlCentro p = null;
FileInputStream fileIn = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileIn);
p = (PnlCentro) in.readObject();
System.out.println("Body: " + p.vecBody);
System.out.println("Life: " + p.life);
System.out.println("Timer: " + p.getTime());
in.close();
fileIn.close();
}
Upvotes: 1
Views: 3154
Reputation: 5488
I think your SaveGame()
and LoadGame
methods work perfectly, they just don't save or load any data from the current game session.
public void SaveGame() throws IOException {
PnlCentro pnlCentro = new PnlCentro(); //<-- Problem likely lies here!
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(pnlCentro);
out.close();
}
Notice the initialization line for pnlCentro
in the SaveGame()
method. The object is declared and instantiated with the default constructor. Unless you have overrode the default constructor to instantiate thepnlCentro
object with the current game data, then the current game data is never set prior to being written out to disk.
Consider this:
public void SaveGame() throws IOException {
PnlCentro pnlCentro = new PnlCentro();
/* Set data prior to writing out */
pnlCentro.setLives(getThisGamesNumLives());
pnlCentro.setTime(getThisGamesTime());
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(pnlCentro);
out.close();
}
Upvotes: 3
Reputation: 2639
In the SaveGame method, you always create a new instance of PnlCentro before serializing, when you use the code:
PnlCentro pnlCentro = new PnlCentro();
There is no modification to the default values of the object plnCentro before the serialization and maybe that's why you are reading zeros after deserialization.
Upvotes: 2