I want to serialize a simple class Person (with name and age) into a file called "somepersons.ser". Basically I want to achieve the behaviour of the following code:
Person p1 = new Person("Person1", 45);
Person p2 = new Person("Person2", 35);
FileOutputStream fos = new FileOutputStream("somepersons.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p1);
oos.writeObject(p2);
oos.close();
FileInputStream fis = new FileInputStream("somepersons.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
p1 = (Person)ois.readObject();
p2 = (Person)ois.readObject();
System.out.println(p1);
System.out.println(p2);
This code stores two Persons in a file, and then recovers and show them on screen. This works as expected.
My problem is: I would like to put the code that stores a Person into a file in a separate method, so you can just call the method with the file pathname and the Person to be serialized as arguments, and the method serializes the passed Person into the file. Basically I want the code to work doing something like this:
Person p1 = new Person("Person1", 45);
Person p2 = new Person("Person2", 35);
FileOutputStream fos = new FileOutputStream("somepersons.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p1);
oos.close();
FileOutputStream fos2 = new FileOutputStream("somepersons.ser");
ObjectOutputStream oos2 = new ObjectOutputStream(fos2);
oos2.writeObject(p2);
oos2.close();
FileInputStream fis = new FileInputStream("somepersons.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
p1 = (Persona)ois.readObject();
p2 = (Persona)ois.readObject();
System.out.println(p1);
System.out.println(p2);
This second piece of code tries to do the same as the first one, but without relying on the existence of an already created FileOutputStream and its correspondant ObjectOutputStream. But when I try to call readObject on ObjectInputStream ois the second time it raises an EOFException, because only one of the objects has been serialized (the second Person). I have tried flushing, resetting, etc. and I get a different Exception but it always fails. I suspect that in this code lies some important serializing concept I don´t quite understand, and I would like for someone to help me shedding some light on it. I have seen similar questions but the answers don´t seem to fit my question. How could I achieve the behaviour of the first piece of code if I don´t want to serialize all objects at the same time? And even more importantly (to improve my understanding of serialization), why this does not work? Thanks!