gpt4 book ai didi

java - append 到 ObjectOutputStream

转载 作者:IT老高 更新时间:2023-10-28 20:25:04 24 4
gpt4 key购买 nike

不能追加到 ObjectOutputStream 吗?

我正在尝试追加到对象列表。以下代码段是一个在作业完成时调用的函数。

FileOutputStream fos = new FileOutputStream
(preferences.getAppDataLocation() + "history" , true);
ObjectOutputStream out = new ObjectOutputStream(fos);

out.writeObject( new Stuff(stuff) );
out.close();

但是当我尝试阅读它时,我只能得到文件中的第一个。然后我得到 java.io.StreamCorruptedException.

阅读我正在使用

FileInputStream fis = new FileInputStream
( preferences.getAppDataLocation() + "history");
ObjectInputStream in = new ObjectInputStream(fis);

try{
while(true)
history.add((Stuff) in.readObject());
}catch( Exception e ) {
System.out.println( e.toString() );
}

我不知道会有多少对象出现,所以我在阅读时没有异常(exception)。根据谷歌的说法,这是不可能的。我想知道是否有人知道方法?

最佳答案

这是诀窍:子类 ObjectOutputStream 并覆盖 writeStreamHeader 方法:

public class AppendingObjectOutputStream extends ObjectOutputStream {

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

@Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}

}

要使用它,只需检查历史文件是否存在并实例化这个可 append 流(如果文件存在 = 我们 append = 我们不需要标题)或原始流(如果文件存在不存在 = 我们需要一个标题)。

编辑

我对类(class)的第一次命名并不满意。这个更好:它描述的是“它的用途”而不是“它是如何完成的”

编辑

再次更改名称,以澄清此流仅用于 append 到现有文件。它不能用于创建带有对象数据的 new 文件。

编辑

this question 之后添加了对 reset() 的调用表明刚刚将 writeStreamHeader 覆盖为无操作的原始版本在某些情况下可能会创建一个无法读取的流。

关于java - append 到 ObjectOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1194656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com