0

I need to append multiple objects in a single file in multiple sessions.

I searched for a fair amount of time and I got two solutions from here.

1) Using List to get already written objects from the file, add new objects to the List and rewriting the file.

2) Overriding writeStreamHeader()

I followed the second method i.e., overriding writeStreamHeader().

He stated that

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.

So I tried this

class ObjectOutput extends ObjectOutputStream
{
    protected ObjectOutput(OutputStream os) throws IOException, SecurityException {
        super(os);
    }

    protected void writeStreamHeader() throws IOException
    {
        File file = new File("abc.txt");
        if(file.exists())
        {
            reset();
        }
        else
        {
            file.createNewFile();
            super.writeStreamHeader();
        }

    }

}

When I try to read the objects from the file there is an exception

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 79737200
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
    at Get.main(Get.java:11)

Then I tried this solution

Now, it worked perfectly!

So, what's wrong with the first code? I called the super.writeStreamHeader() when there is no file and the second method also calls the same method in the same scenario.

So,is there anything I am missing?

Thank you.

Community
  • 1
  • 1
  • 1
    If the file doesn't exist you can't possibly enter this piece of code. It will have been created by `new FileOutputStream(...)` before this constructor executes. – user207421 Jul 17 '16 at 12:20
  • @EJP yeah I completely missed that point. Thank you! –  Jul 17 '16 at 15:47

1 Answers1

0

You can do this too and still it will work fine

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class MyObjectOutputStream extends ObjectOutputStream {
    public MyObjectOutputStream() throws IOException{
       super();
    }
    public MyObjectOutputStream(OutputStream outputStream) throws IOException{
        super(outputStream);
     }
   public void writeStreamHeader(){}
 }

The explanation for this is the same as the link to the solution you provided in the question itself.