将对象附加到序列化文件

时间:2013-03-25 05:01:02

标签: java object serialization

假设您有一些AppendObjectOutputStream类(它是一个ObjectOutputStream!),它会覆盖writeStreamHeader(),如下所示:

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

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

2 个答案:

答案 0 :(得分:8)

您必须首次使用常规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());

答案 1 :(得分:0)

以上对我不起作用,特别是 reset() 不起作用。 我在这里找到了以下内容: https://coderanch.com/t/583191/java/ObjectOutputStream-appending-file-overiding-ObjectOutputStream

@Override 
protected void writeStreamHeader() throws IOException {  
   // TODO Auto-generated method stub  
   System.out.println("I am called");  
   super.writeStreamHeader();
}  

这对我有用。我知道这似乎违反直觉,乍一看似乎调用超类方法不应该做任何事情,但确实如此。阅读原帖并尝试一下。