Consider the code segment :
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("students-objects.txt", true); //always append
oos = new ObjectOutputStream(fos);
for(int i = 0; i < list.size(); i++ ) {
oos.writeObject(list.get(i);
}
oos.flush();
}
catch (IOException io) {
io.printStackTrace();
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
}
catch (IOException e) {}
}
If I call the previous code segment more than once with a list of Serializable objects every thing seems fine until I try to read from the file. It reads the list of elements written first correctly, then fails throwing a StreamCorruptedException with the following stack trace :
java.io.StreamCorruptedException
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at ObjectStreamExample.readStudentInfo(ObjectStreamExample.java:40)
at ObjectStreamExample.main(ObjectStreamExample.java:72)
I am seeing this behavior in JDK 1.4 and 1.5. Is this a desired behavior? If so, does anyone know why? Is there a better workaround then rewriting the current contents each time you write?