Appending Objects to a serialization file
Suppose you have some AppendObjectOutputStream class (which is an ObjectOutputStream!) which overrides writeStreamHeader() like this:
@Override
public void writeStreamHeader() throws IOException
{
reset();
}
Now also, let's say you plan on saving multiple objects to a file; one object for each time your program runs. Would you, even on the first run, use AppendObjectOutputStream()?
You have to write the stream header first time with regular ObjectOutputStream otherwise you will get java.io.StreamCorruptedException on opening the file with ObjectInputStream.
public class Test1 implements Serializable {
public static void main(String[] args) throws Exception {
ObjectOutputStream os1 = new ObjectOutputStream(new FileOutputStream("test"));
os1.writeObject(new Test1());
os1.close();
ObjectOutputStream os2 = new ObjectOutputStream(new FileOutputStream("test", true)) {
protected void writeStreamHeader() throws IOException {
reset();
}
};
os2.writeObject(new Test1());
os2.close();
ObjectInputStream is = new ObjectInputStream(new FileInputStream("test"));
System.out.println(is.readObject());
System.out.println(is.readObject());