1

Desclaimer My question is different from two following links

Question 1

Question 2

    public class AppendableObjectOutputStream extends ObjectOutputStream {
      public AppendableObjectOutputStream(OutputStream out) throws IOException {
        super(out);
      }

      @Override
      protected void writeStreamHeader() throws IOException {}
}
  • The problem with above solutions is that they do not support writing multiple objects to appendable stream w/o closing the stream.
  • If I open appendable stream, write multiple objects - then at time of reading I can read only first object properly and on trying to read second object, I get EOF exception.
  • If I proceed the way like write on object to appendable stream, close stream. Then again open stream, write another object close and so on. This way I am able to read multiple objects properly.

        fileOutputStream = new FileOutputStream("abc.dat",true);
         outputBuffer = new BufferedOutputStream(fileOutputStream);
         objectStream = new AppendableObjectOutputStream(outputBuffer);
         BucketUpdate b1 = new BucketUpdate("getAllProducts1",null,"1",null);
         BucketUpdate b2 = new BucketUpdate("getAllProducts2",null,"2",null);
         BucketUpdate b3 = new BucketUpdate("getAllProducts3",null,"3",null);
         objectStream.writeObject(b1);
         objectStream.writeObject(b2);
         objectStream.writeObject(b3);
         objectStream.close();
    
Community
  • 1
  • 1
MoveFast
  • 3,011
  • 2
  • 27
  • 53

2 Answers2

5

Calling ObjectOutputStream.reset() after writing each object will fix this.

Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
4

If you check question you mentioned, you will see that you have to use AppendableObjectOutputStream only to append objects to file, if file already contains some objects. For empty file you have to use ordinary ObjectOutputStream because the header should be written to the beginning in this case.

Community
  • 1
  • 1
Sergey Aslanov
  • 2,397
  • 15
  • 16