追加到一个ObjectOutputStream [英] Appending to an ObjectOutputStream

查看:137
本文介绍了追加到一个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

要读我使用

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

我不知道有多少对象,怎么会present所以我读书时,没有异常。从什么谷歌说,这是不可能的。我不知道是否有人知道的方式?

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) {
    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.

修改

添加一个电话复位()在<一个href=\"http://stackoverflow.com/questions/12279245/classcastexception-when-appending-object-outputstream/12438141#12438141\">this问题表明,仅仅覆盖了原来的版本 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天全站免登陆