附加到 ObjectOutputStream [英] Appending to an ObjectOutputStream

查看:38
本文介绍了附加到 ObjectOutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能附加到 ObjectOutputStream 吗?

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

I am trying to append to a list of objects. Following snippet is a function that is called whenever a job is finished.

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

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

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

But when I try to read it I only get the first in the file. Then I get 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() );
}

我不知道会有多少对象出现,所以我正在阅读,没有例外.从谷歌所说这是不可能的.我想知道有没有人知道方法?

I do not know how many objects will be present so I am reading while there are no exceptions. From what Google says this is not possible. I was wondering if anyone knows a way?

推荐答案

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

Here's the trick: subclass ObjectOutputStream and override the writeStreamHeader method:

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

}

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

To use it, just check whether the history file exists or not and instantiate either this appendable stream (in case the file exists = we append = we don't want a header) or the original stream (in case the file does not exist = we need a header).

编辑

我对课程的第一个命名并不满意.这个更好:它描述了它的用途"而不是它是如何完成的"

I wasn't happy with the first naming of the class. This one's better: it describes the 'what it's for' rather then the 'how it's done'

编辑

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

Changed the name once more, to clarify, that this stream is only for appending to an existing file. It can't be used to create a new file with object data.

编辑

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

Added a call to reset() after this question showed that the original version that just overrode writeStreamHeader to be a no-op could under some conditions create a stream that couldn't be read.

这篇关于附加到 ObjectOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆