10

至于现在,java.io.StreamCorruptedException当我尝试附加一个对象时我会得到。我已经在互联网上搜索了一种方法来克服它。到目前为止我找到的答案是无法完成。解决此问题的一种方法是将对象写入列表,然后将列表写入文件。

但是每次添加新对象时,我都必须覆盖该文件。这似乎不是加班的最佳解决方案。

有没有办法将对象附加到现有的对象流?

4

4 回答 4

5

这实际上很容易做到。当您添加到现有流时,您需要使用覆盖的 ObjectOutStream 的子类,writeStreamHeader以便不会在文件中间写入第二个标头。例如

class NoHeaderObjectOutputStream extends ObjectOutputStream {
  public NoHeaderObjectOutputStream(OutputStream os) {
    super(os);
  }
  protected void writeStreamHeader() {}
}

然后只需使用标准 ObjectInputStream 来读取整个文件。

于 2010-01-19T16:44:36.260 回答
5

我在这个主题上找到的最好的文章是: http ://codify.flansite.com/2009/11/java-serialization-appending-objects-to-an-existing-file/

覆盖 ObjectOutputStream 的“解决方案”是完全错误的。我刚刚完成了一个由此引起的错误的调查(浪费了宝贵的两天时间)。它不仅有时会损坏序列化文件,而且甚至可以在不引发异常的情况下进行读取,并最终提供垃圾数据(混合字段)。对于那些不相信的人,我附上了一些暴露问题的代码:

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws Exception {

        File storageFile = new File("test");
        storageFile.delete();

        write(storageFile, getO1());
        write(storageFile, getO2());
        write(storageFile, getO2());

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(storageFile));
        read(ois, getO1());
        read(ois, getO2());
        read(ois, getO2());
    }

    private static void write(File storageFile, Map<String, String> o) throws IOException {
        ObjectOutputStream oos = getOOS(storageFile);
        oos.writeObject(o);
        oos.close();
    }

    private static void read(ObjectInputStream ois, Map<String, String> expected) throws ClassNotFoundException, IOException {
        Object actual = ois.readObject();
        assertEquals(expected, actual);
    }

    private static void assertEquals(Object o1, Object o2) {
        if (!o1.equals(o2)) {
            throw new AssertionError("\n expected: " + o1 + "\n actual:   " + o2);
        }
    }

    private static Map<String, String> getO1() {
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("timestamp", "1326382770000");
        nvps.put("length", "246");
        return nvps;
    }

    private static Map<String, String> getO2() {
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("timestamp", "0");
        nvps.put("length", "0");
        return nvps;
    }

    private static ObjectOutputStream getOOS(File storageFile) throws IOException {
        if (storageFile.exists()) {
            // this is a workaround so that we can append objects to an existing file
            return new AppendableObjectOutputStream(new FileOutputStream(storageFile, true));
        } else {
            return new ObjectOutputStream(new FileOutputStream(storageFile));
        }
    }

    private static class AppendableObjectOutputStream extends ObjectOutputStream {

        public AppendableObjectOutputStream(OutputStream out) throws IOException {
            super(out);
        }

        @Override
        protected void writeStreamHeader() throws IOException {
            // do not write a header
        }
    }
}

如该文章所述,您可以使用以下解决方案之一:

解决方案 #1:在单个流中伪造多个文件

...

将您的“事务”写入 ByteArrayOutputStream,然后通过 DataOutputStream 将此 ByteArrayOutputStream 的长度和内容写入文件。

解决方案#2:重新打开并跳过

另一种解决方案涉及使用以下方法保存文件位置:

long pos = fis.getChannel().position();

关闭文件,重新打开文件,然后在读取下一个事务之前跳到这个位置。

于 2012-01-13T18:15:03.000 回答
3

非常感谢George Hategan解决暴露代码的问题。我也检查了一段时间。然后,它击中了我。如果您使用重写了writeStreamHeader()方法的子类ObjectOutputStream来写入数据,则必须使用重写了readStreamHeader()方法的并行子类ObjectInputStream来读取数据。当然,我们可以在写入和读取对象的不同实现之间进行曲折,但只要我们在写入/读取过程中使用相应的子类对 - 我们(希望)会很好。汤姆。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class SerializationDemo {

    public static void main(String[] args) throws Exception {
        File storageFile = new File("test.ser");
        storageFile.delete();
        write(storageFile, getO1());
        write(storageFile, getO2());
        write(storageFile, getO2());
        FileInputStream fis = new FileInputStream(storageFile);
        read(fis, getO1());
        read(fis, getO2());
        read(fis, getO2());
        fis.close();
    }

    private static void write(File storageFile, Map<String, String> o)
                    throws IOException {
        ObjectOutputStream oos = getOOS(storageFile);
        oos.writeObject(o);
        oos.flush();
        oos.close();
    }

    private static void read(FileInputStream fis, Map<String, String> expected)
                    throws ClassNotFoundException, IOException {
        Object actual = getOIS(fis).readObject();
        assertEquals(expected, actual);
        System.out.println("read serialized " + actual);
    }

    private static void assertEquals(Object o1, Object o2) {
        if (!o1.equals(o2)) {
            throw new AssertionError("\n expected: " + o1 + "\n actual:   " + o2);
        }
    }

    private static Map<String, String> getO1() {
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("timestamp", "1326382770000");
        nvps.put("length", "246");
        return nvps;
    }

    private static Map<String, String> getO2() {
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("timestamp", "0");
        nvps.put("length", "0");
        return nvps;
    }

    private static ObjectOutputStream getOOS(File storageFile)
                    throws IOException {
        if (storageFile.exists()) {
            // this is a workaround so that we can append objects to an existing file
            return new AppendableObjectOutputStream(new FileOutputStream(storageFile, true));
        } else {
            return new ObjectOutputStream(new FileOutputStream(storageFile));
        }
    }

    private static ObjectInputStream getOIS(FileInputStream fis)
                    throws IOException {
        long pos = fis.getChannel().position();
        return pos == 0 ? new ObjectInputStream(fis) : 
            new AppendableObjectInputStream(fis);
    }

    private static class AppendableObjectOutputStream extends
                    ObjectOutputStream {

        public AppendableObjectOutputStream(OutputStream out)
                        throws IOException {
            super(out);
        }

        @Override
        protected void writeStreamHeader() throws IOException {
            // do not write a header
        }
    }

    private static class AppendableObjectInputStream extends ObjectInputStream {

        public AppendableObjectInputStream(InputStream in) throws IOException {
            super(in);
        }

        @Override
        protected void readStreamHeader() throws IOException {
            // do not read a header
        }
    }
}
于 2012-03-15T23:38:31.327 回答
0

您需要创建一个新ObjectInputStream的以匹配每个ObjectOutputStream. 我不知道将状态从完整传输到完整ObjectInputStream的方法ObjectOutputStream(没有完整的重新实现,无论如何这在纯 Java 中有点棘手)。

于 2010-01-19T16:02:18.530 回答