问题描述
假设您有一些AppendObjectOutputStream类(它是一个ObjectOutputStream!),它会覆盖writeStreamHeader(),如下所示:
Suppose you have some AppendObjectOutputStream class (which is an ObjectOutputStream!) which overrides writeStreamHeader() like this:
@Override
public void writeStreamHeader() throws IOException
{
reset();
}
现在,假设您计划将多个对象保存到文件中;每次程序运行时都有一个对象。即使在第一次运行时,您是否会使用AppendObjectOutputStream()?
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()?
推荐答案
您必须首次定期编写流标头ObjectOutputStream否则在使用ObjectInputStream打开文件时会得到java.io.StreamCorruptedException。
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());
这篇关于将对象附加到序列化文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!