Satyaki Satyaki - 28 days ago 18
Java Question

Deserialization In Java

I serialized a file with multiple objects. So I wrote a code like below -

FileOutputStream outputStream=new FileOutputStream(new File("Output.ser"));
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(employee);
objectOutputStream.writeObject(employee2);
objectOutputStream.writeObject(employee3);
objectOutputStream.writeObject(employee4);
objectOutputStream.close();


Now I want to de-serialize it, so to do that I took the help of WHILE loop to loop through all the objects ! The Code looks like below -

FileInputStream fileInputStream=new FileInputStream(new File(fileName));
ObjectInputStream stream=new ObjectInputStream(fileInputStream);
Employee emp;
while((emp=(Employee) stream.readObject())!=null)
{
String uName=emp.getUserId();
String uPass=emp.getPassword();
map.put(uName, uPass);
}


This code making an EOFException reaching the end of file. I guess readObject() should return a null when it reaches the end of the file but in this case it ended up throwing an exception!
Please do suggest me way(s) by which I can successfully read my serialized file without getting any exception!

Answer

Instead of serializing multiple objects, you should serialize a List like so :

FileOutputStream outputStream=new FileOutputStream(new File("Output.ser"));
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(employee);
employees.add(employee2);
employees.add(employee3);
employees.add(employee4);
objectOutputStream.writeObject(employees);
objectOutputStream.close();

You can deserialize it like so :

FileInputStream fileInputStream=new FileInputStream(new File(fileName));
ObjectInputStream stream=new ObjectInputStream(fileInputStream);
for(Employee emp : (ArrayList)stream.readObject())
{
    String uName = emp.getUserId();
    String uPass = emp.getPassword();
    map.put(uName, uPass);
}