java 将对象附加到序列化文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15607969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:15:05  来源:igfitidea点击:

Appending Objects to a serialization file

javaobjectserialization

提问by Mike Warren

Suppose you have some AppendObjectOutputStream class (which is an ObjectOutputStream!) which overrides writeStreamHeader() like this:

假设您有一些 AppendObjectOutputStream 类(它是一个 ObjectOutputStream!),它像这样覆盖 writeStreamHeader():

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

现在,假设您计划将多个对象保存到一个文件中;程序每次运行时对应一个对象。即使在第一次运行时,您也会使用 AppendObjectOutputStream() 吗?

回答by Evgeniy Dorofeev

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.

您必须第一次使用常规 ObjectOutputStream 编写流标头,否则在使用 ObjectInputStream 打开文件时您将得到 java.io.StreamCorruptedException。

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