Xaini Ali Xaini Ali - 7 months ago 12
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(){
try{
FileOutputStream fs=new FileOutputStream("S.txt");
ObjectOutputStream os=new ObjectOutputStream(fs);
os.writeObject(teachers);

os.close();
}catch(Exception e)
{System.out.println(e);}

}


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

return;
}
}

Answer

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
Comments