Joseph Erickson
Joseph Erickson

Reputation: 960

Save Game data - Java

I've created a rudimentary game with a few objects. I'd like to give the user of the program the ability to save and load the state of the program.

I've researched multiple articles and read through a lot of overstack posts. I was surprised by the amount of methods, and the complexity of each of those methods.

Most methods require that I create the framework or skeleton of all objects that I want to save, and then load them line by line, calling each object manually, and then casting it back into its data type and class.

Yes, I'm new to programming. But I'm not asking for a handout. I'm asking for a concise explanation.

I read the below article, as I explored the idea of outputting to an XML file.

http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

As I stated, I'm new to programming. Should I be learning XML in tandem with Java?

My question is the following:

A) Doesn't my IDE, upon successful compilation, know how many objects I have, their data type, and what class they belong to?

B) Is there a way to save ALL objects without specifying them individually.

c) Have I overdramitized the complexity of saving a simple program?

Upvotes: 7

Views: 26876

Answers (3)

Radiodef
Radiodef

Reputation: 37845

Should I be learning XML in tandem with Java?

There's no reason to unless you want to learn XML or think XML is a good option for your application. There are many ways to serialize without XML.

Doesn't my IDE, upon succesful compilation, know how many objects I have, their data type, and what class they belong to?

No, it doesn't have to. Since allocations are done dynamically in Java, there are situations where it's even impossible to know this information statically.

Foo[] foos = new Foo[ new Scanner(System.in).nextInt() ];
for(int i = 0; i < foos.length; ++i)
    foos[i] = new Foo();

(How many Foos were created? The compiler doesn't know.)

Certainly the compiler knows a lot about the types of data.

B) Is there a way to save ALL objects without specifying them individually.

Maybe with Serializable. Basically you will put all your program state inside a single object. When you serialize that single object, everything else gets serialized recursively.

class FooState implements Serializable {
    Integer a, b, c; // Integer and String
    String d, e, f;  // also implement Serializable
}

class Foo {
    static FooState allMyState = new FooState();

    public static void main(String[] args) throws IOException {
        try(ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(new File("myFile.data")))) {
            // no need to specify members individually
            oos.writeObject(allMyState);
        }
    }
}

The same concept probably applies to other serialization schemes like JSON, XML, etc.

You need to think carefully about what you put in the state object since everything in it will get saved.

c) Have I overdramitized the complexity of saving a simple program?

Not really. Saving program state can be complicated if it's not just a few values.

Upvotes: 6

prasad vsv
prasad vsv

Reputation: 1168

Have a class that can save the current state of the game.

public class Game{
    int coOrdinateX;
    int coOrdinateY;
    int score;
    String[] powersCurrentlyTheUserHad;
    ...
}

when ever user exits, load this class with relevant data. As once the game terminates, memory vanishes, you need to save this in a file.

Serialization is a way of storing Objects to disk(essentially into files), such that, when you de-serialize using the library functions, you directly get back the object with the current state.

check http://www.tutorialspoint.com/java/java_serialization.htm for more details

Upvotes: 0

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

A) Doesn't my IDE, upon succesful compilation, know how many objects I have, their data type, and what class they belong to?

Loading the state of the program has nothing to do with IDE or compilation. You start your program and it's already running, you want to change it's state by loading some state from the file.

If you use serialization, you may face problems related to versions and classes incompatibility - e.g. if you decide to add a new field to a class, you will need to write extra code to be able to load an older state, which didn't have that field. So other format such as XML, JSON or plain text (and doing the conversion yourself) may be better idea.

B) Is there a way to save ALL objects without specifying them individually.

Well, theoretically it should be possible to save the state of entire JVM and load it back later. It's an advanced topic and there would be a lot of problems because of all clever stuff going on inside JVM (such as Just-In-Time compiler, garbage collection and various on-the-fly optimizations). I don't recommend going down this way. Most probably, you won't be able to change your code at all - e.g. if you add new button in your GUI, the loaded version will not have it, because it will be loading old versions of the classes. So it won't be possible to load an old game state into new version of the game.

C) Have I overdramitized the complexity of saving a simple program?

Let's say that your game has class called Game with constructor Game(String name) (and some other parameters). For the first time, you can create it by just calling new Game("firstGame"). But now you want to create this object from some saved state. You can either serialize the object and then load it back, the result will be the object itself. Or you can read the file to get that string and just call the constructor yourself using this string. Going further this way there are libraries that can convert object to JSON and JSON to object (such as Jackson serializer).

Upvotes: 2

Related Questions