An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.


As the API says, the ObjectOutputStream constructor writes the serialization stream header to the underlying stream. And this header is expected to be only once, in the beginning of the file. So calling
new ObjectOutputStream(fos);
multiple times on the FileOutputStream that refers to the same file will write the header multiple times and corrupt the file.
So in order to append the Object to the file, you can code like this:

public class AppendingObjectOutputStream extends ObjectOutputStream {

  public AppendingObjectOutputStream(OutputStream out) {
    super(out);
  }
  @Override
  protected void writeStreamHeader() throws IOException {
    // do not write a header, but reset:

    reset();
  }
}

Any time you want to append, just simply create new Object from this class and call its writeObject() method.

►►សូមអរគុណរាល់ការចូលរួមCommentរបស់អ្នក!

 
Top
Don't You Think this Awesome Post should be shared ??
| Write and Append Object to binary file with ObjectOutputStream [Java Programming] |