Search code examples
javaobjectinputstreamobjectoutputstream

Appending to an ObjectOuputStream


I have a file by the name "admin_product.bin". I want to append objects to the file. After searching I found a class as follows:

public class AppendingObjectOutputStream extends ObjectOutputStream {

  public AppendingObjectOutputStream(OutputStream out) throws IOException {
    super(out);
  }

  @Override
  protected void writeStreamHeader() throws IOException {
    // do not write a header, but reset:
    // this line added after another question
    // showed a problem with the original
    reset();
  }

}

The above code helped we append data to my file. However when I try to read the file using ObjectInputStream, it throws an error as follows:

java.io.StreamCorruptedException: invalid stream header: 79737200

My code sample is:

public static void write_into_file() throws IOException {
        File file = null;
        file = new File("admin_product.bin");

        if(!file.exists()) {
            ObjectOutputStream os = null;
            try {
                os = new ObjectOutputStream(new FileOutputStream(file));
                os.writeObject(prd);
                System.out.println("Done!");
            } catch(Exception e) {
                System.out.println("Exception = " + e);
            } finally {
                if(os != null) {
                    os.close();
                }
            }

        }

        else {
            AppendingObjectOutputStream as = null;
            try {
                as = new AppendingObjectOutputStream(new FileOutputStream(file));
                as.writeObject(prd);
                System.out.println("Done!");
            } catch(Exception e) {
                System.out.println("Exception = " + e);
            } finally {
                if(as != null) {
                    as.close();
                }
            }
        }
    }

Can anyone please tell me where I am going wrong?

I have the answers from the following questions (yet couldn't figure out the problem) -

1) Appending to a file

2) Appending class error


Solution

  • You are not appending to the file. If you are appending to the object stream, you must also append to the file and not overwrite what is already there.

    This will overwrite the existing file contents:

    new FileOutputStream(file)
    

    To append use

    new FileOutputStream(file, true)
    

    The whole line would be:

    as = new AppendingObjectOutputStream(new FileOutputStream(file, true));