Search code examples
javaserializable

Serializable on ArrayList losing some data


I have an ArrayList of Employee objects where Employee class implements Serializable. I am using this code to write lists to a file:

ArrayList<Employee> empList = new ArrayList<>();
  FileOutputStream fos = new FileOutputStream("EmpObject.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  // write object to file
  empList .add(emp1);
  empList .add(emp2);
  oos.writeObject(empList);

  empList .add(emp3);

  oos.writeObject(empList);
}

If I try to de-serialize it I am just getting first two objects not the 3rd one. Can anyone please try why is it?

edit1: If I add all elements at once everything is fine but not the way I did first. What is the difference?

ArrayList<Employee> empList = new ArrayList<>();
  FileOutputStream fos = new FileOutputStream("EmpObject.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  // write object to file
  empList .add(emp1);
  empList .add(emp2);
  empList .add(emp3);
  oos.writeObject(empList);
}

After this I have 3 elements


Solution

  • As GhostCat and uaraven already mentioned reset does not what you are expecting it to do and you should have a look at a tutorial on serialization and maybe consider using sth. else if this isn't fitting your use case.

    Your code could look as follows if creating a new FileOutputStream:

    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    
    public class SerializationTest {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            String path = "EmpObject.ser";
    
            ArrayList<Employee> empList = new ArrayList<>();
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
    
            empList.add(emp1);
            empList.add(emp2);
            oos.writeObject(empList);
    
            empList.add(emp3);
            // Create a new FileOutputStream to override the files content instead of appending the new employee list
            oos = new ObjectOutputStream( new FileOutputStream(path));
            oos.writeObject(empList);
    
            ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream(path));
            List<Employee> readCase = (List<Employee>) objectinputstream.readObject();
    
            System.out.println(readCase);
        }
    }