Save and Load – success

Seriously, I thought I would have to pick it up again at a later point, but after drinking a good sip of whiskey, I finally found the right solution.

My problem with saving and loading the world object (which contains a two-dimensional array of WorldCells, aswell as a two-dimensional array of the Tile (enum)). I totally started it the wrong way. I wanted it to output into an xml file. I used XStream for the serialization and deserialization. It gave me an xml file, 38 mb huge and of course readable and editable, which I didnt want. I succeeded, after many hours, to save the world as I wanted it, but then - this was my biggest problem- I couldn't load the file back. I was browsing the web for hours reading about enum converters and stuff. All too complicated!

Today I sat down and after 10 minutes I was done.
What did I do?
It's easy:

Java has an own Serialization Interface which needs to be implemented to the class that gets saved.


public class World implements Serializable {
...
}


The rest was so easy, using ObjectOutputStream and ObjectInputStream, aswell as selecting the destination file.


public void saveWorld(World world){
try {
FileOutputStream f_out = new FileOutputStream("save/world.sav");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);

obj_out.writeObject ( world );
obj_out.flush();
obj_out.close();
System.out.println("world saved successfully");

} catch (IOException e) {
e.printStackTrace();
}
}

public void loadWorld(){
try {

FileInputStream f_in = new FileInputStream("save/world.sav");
ObjectInputStream obj_in = new ObjectInputStream (f_in);

this.world = (World) obj_in.readObject();
obj_in.close();
System.out.println("world loaded successfully");

} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}


  Now it works! Currently it goes on a Key Input (World now takes 2 seconds to load or save using ObjectInput, XStream/xml took already 6 seconds to save). I will write this up on the start screen, so the player can't accidentally load a new game while he is playing. More Whiskey!

Leave a Reply

Your email address will not be published. Required fields are marked *