Xaini Ali Xaini Ali - 2 years ago 80
Java Question

Deserializing an ArrayList with multiple objects

I have stored multiple objects in Teacher ArrayList and I'm trying to deserialize it, but it shows the garbage value.

public void Write(){
FileOutputStream fs=new FileOutputStream("S.txt");
ObjectOutputStream os=new ObjectOutputStream(fs);

}catch(Exception e)


public void Read(){
FileInputStream fis = new FileInputStream("E:\\Books\\OOP\\Teacher\\S.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
teachers = (ArrayList<Teacher>) ois.readObject();
for(Teacher i: teachers){
}catch(IOException ioe){
}catch(ClassNotFoundException c){
System.out.println("Class not found");


Answer Source

You are using object streams, which persist your serialized objects in binary, regardless of the extension of the file (which happens to be ".txt" here, ambiguously suggesting that it'll be a text file when written).

You cannot view anything human-like from your file with a text editor when the data written is binary data.

If your "garbage values" also get printed when you iterate your List<Teacher> upon de-serialization, it implies that:

  1. (De-)serialization actually succeeded (i.e. you've written your List<Teacher> to file and retrieved it)
  2. Your Teacher class might not override toString properly or at all, so it prints the Type@hashCode notation from Object#toString when fed to the system output print stream
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download