我怎样才能添加到现有的java

我怎样才能添加到现有的java

本文介绍了我怎样才能添加到现有的java.io.ObjectStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

至于现在我将获得 java.io.StreamCorruptedException 当我尝试追加一个对象。我已经在网上搜索一种方式来克服。我迄今发现答案是不能完成的。解决这个问题的一个方法是把对象写入到一个列表,然后写列表以文件

As for now I will get java.io.StreamCorruptedException when I try to append an Object. I have searched the Internet for a way to overcome that. The answer I found so far is it can't be done. A way around this problem is to write the objects into a list and then write the list to the file.

但我有当我添加新的对象覆盖该文件每次。它似乎不是在加时赛中的最佳解决方案。

But I have to overwrite that file everytime when I add new objects. It seems not to be the optimal solution in overtime.

有没有一种方法追加对象到现有对象流?

Is there a way to append objects to an existing object stream?

推荐答案

它实际上是pretty容易做到的。当您添加到现有的流,你需要使用ObjectOutStream的子类,覆盖 writeStreamHeader 使第二头不会在文件的中间写入。例如:

It is actually pretty easy to do. When you are adding to an existing stream you need to use a subclass of ObjectOutStream that overrides writeStreamHeader so that a second header is not written in the middle of the file. For example

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

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

Then just use a standard ObjectInputStream to read the whole file.

这篇关于我怎样才能添加到现有的java.io.ObjectStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:52