How can I append to an existing java.io.ObjectStream?

starcorn picture starcorn · Jan 19, 2010 · Viewed 9.5k times · Source

As for now I will get java.io.StreamCorruptedException when I try to append an Object. I have searched the Internet for a way to overcome that. The answer I found so far is it can't be done. A way around this problem is to write the objects into a list and then write the list to the file.

But I have to overwrite that file everytime when I add new objects. It seems not to be the optimal solution in overtime.

Is there a way to append objects to an existing object stream?

Answer

Geoff Reedy picture Geoff Reedy · Jan 19, 2010

It is actually pretty easy to do. When you are adding to an existing stream you need to use a subclass of ObjectOutStream that overrides writeStreamHeader so that a second header is not written in the middle of the file. For example

class NoHeaderObjectOutputStream extends ObjectOutputStream {
  public NoHeaderObjectOutputStream(OutputStream os) {
    super(os);
  }
  protected void writeStreamHeader() {}
}

Then just use a standard ObjectInputStream to read the whole file.