javaobjectoutputstreamobject-files

Appending Items to an object file


I know there are similar questions but none of them have helped me as I tried their methods and it is simply not working. I would appreciate any advice on this topic

I am having trouble appending objects to an object file. I am trying to do a registration process and I'm using this method to write to the Object file.

public void WriteObjectToFile(Object serObj, String filepath) { 

    try {
        boolean exists;
        if(!(new File(filepath).isFile())){
            exists = false;
        }else{
            exists = true;
        }
        FileOutputStream fileOut = new FileOutputStream(filepath);
        ObjectOutputStream objectOut = null;
        if(!exists){
            System.out.println("Normal");
            objectOut = new ObjectOutputStream(fileOut);
        }else{
            System.out.println("Custom");
            objectOut = new AppendingObjectOutputStream(fileOut);
        }
        objectOut.writeObject(serObj);
        objectOut.close();
        System.out.println("The Object  was succesfully written to a file");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

The custom AppendingObjectOutputStreamClass looks like this:

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

public class AppendingObjectOutputStream extends ObjectOutputStream {

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

@Override
protected void writeStreamHeader() throws IOException {
    reset();
}

}

the if statement checks if the file exists. If it doesn't then it means that it is the first object and thus i use the normal ObjectOutputStream. If it is not the first then I use the custom AppendingObjectOutputStream, however this still gives me a StreamCorruptedErrorException.

Any help on this would be greatly appreciated.


Solution

  • Replace

    FileOutputStream fileOut = new FileOutputStream(filepath);
    

    with

    FileOutputStream fileOut = new FileOutputStream(filepath,true);
    

    Check https://docs.oracle.com/javase/9/docs/api/java/io/FileOutputStream.html#FileOutputStream-java.io.File-boolean- for more details.