Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...