1

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?

Thanks

asked Aug 10, 2016 at 23:46

2 Answers 2

3

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);
 oos.writeObject(saved);
 oos.flush();
 oos.close();
 fos.close();
 FileInputStream fis = new FileInputStream("test.obj");
 ObjectInputStream ois = new ObjectInputStream(fis);
 HashMap<String,Object> retreived = (HashMap<String,Object>)ois.readObject();
 fis.close();
 System.out.println(retreived.get("A"));
 System.out.println(retreived.get("B"));
 } catch (IOException e) {
 e.printStackTrace();
 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 }
}

Running this should result in:

first
second
answered Aug 11, 2016 at 0:01
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this looks like it has worked. Instead of just printing out "A" and "B" into the console how as assign it back to an object I can do things with?
I figured it out from here: stackoverflow.com/questions/7857935/… Thanks again for your answer it put me on the right track :)
0

Just call writeObject() as many times with as many different objects as you need, and conversely call readObject() ditto.

Hard to believe you haven't already tried it.

answered Aug 10, 2016 at 23:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.