Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 688
Mike Warren Avatar asked Mar 25 '13 05:03

Mike Warren


People also ask

Can you customize serialization?

Customized serialization can be implemented using the following two methods: private void writeObject(ObjectOutputStream oos) throws Exception: This method will be executed automatically by the jvm(also known as Callback Methods) at the time of serialization.

What happens if the object to be serialized?

To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

What is purpose of serialization of an object?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.


1 Answers

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());
like image 109
Evgeniy Dorofeev Avatar answered Oct 05 '22 04:10

Evgeniy Dorofeev