jprogrammer jprogrammer - 1 year ago 123
Java Question

Serialize multiple different objects single in Java

I might be trying to do this the hard way so let me know if there is a better solution.

I am making a simple text game in Java which you select your actions by a GUI. I have a couple of classes I am trying to serialize one being the player and another being an NPC. Is there an easy way to serialize more then one object (player and NPC) into the same file? I can serialize one object and load it back into the game.

Am I going about this the wrong way? Is there a simpler way of trying to save the game state?

If I have a class that creates multiple objects and I serialize that class, will the objects it created be serialized as well?


Answer Source

An alternate approach to writing objects sequentially is to store them in a collection (e.g. a HashMap), since collections can be serialized. This may make it a little easier to manage upon retrieval, especially if you have many objects to serialize/deserialize. The following code demonstrates this:

    String first = "first";
    String second = "second";
    HashMap<String, Object> saved = new HashMap<String, Object>();
    saved.put("A", first);
    saved.put("B", second);

    try {
        FileOutputStream fos = new FileOutputStream("test.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        FileInputStream fis = new FileInputStream("test.obj");
        ObjectInputStream ois = new ObjectInputStream(fis);

        HashMap<String,Object> retreived = (HashMap<String,Object>)ois.readObject();

    } catch (IOException e) {
    } catch (ClassNotFoundException e) {

Running this should result in: