Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Appending to a file containing serialized Objects?  RSS feed

 
Scott Corley
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

# Why can't a file that contains multiple appended ObjectOutputStreams be deserialized by one ObjectInputStream?

Using the default implementation of serialization, there must be a one-to-one mapping between ObjectOutputStream construction and ObjectInputStream construction. ObjectOutputStream constructor writes a stream header andObjectInputStream reads this stream header. A workaround is to subclass ObjectOutputStream and override writeStreamHeader(). The overriding writeStreamHeader() should call the super writeStreamHeader method if it is the first write to the file and it should call ObjectOutputStream.reset() if it is appending to a pre-existing ObjectOutputStream within the file.

Object Serialization: Frequently Asked Questions
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!