views:

206

answers:

2

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 a way to append objects to an existing object stream?

A: 

You would need to create a new ObjectInputStream to match every ObjectOutputStream. I don't know a way to transfer state from a complete ObjectInputStream to an ObjectOutputStream (without a complete reimplementation, which is a bit tricky in pure Java anyway).

Tom Hawtin - tackline
+4  A: 

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.

Geoff Reedy
Very nice, void write(byte[] b, int off, int len, boolean copy) uses unfortunatly private method writeBlockHeader.
stacker
nice, it works :)
starcorn
+1 I read that in the documentation but ( as it often happens me with documentation ) I didn't quite get it, until now.
OscarRyz
@stacker I don't see how that causes any problem. That header is part of the format of the serialized stream to say read the next n bytes as a single byte array and will be read properly when consuming the stream later.
Geoff Reedy
Excellent tip, Geoff. Once again, SO makes me aware of a new technique
Kevin Day