首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >追加到ObjectOutputStream

追加到ObjectOutputStream
EN

Stack Overflow用户
提问于 2017-10-24 04:04:47
回答 1查看 934关注 0票数 0

我有一个利用memento设计模式的程序,希望使用序列化将每个对象的状态保存到一个文件中,并返回该对象。问题是我得到了一个"java.io.StreamCorruptedException: invalid type code: AC“异常,因为报头损坏。我查看了Appending to an ObjectOutputStream并尝试实现该类,但仍然无法使程序正常工作。多个对象应该保存在一个文件中,并且用户将一个字符串传递给一个函数,该函数应该与对象的字符串表示的一部分相匹配。

代码语言:javascript
复制
public class Caretaker implements Serializable {
public void addMemento(Memento m) {
    try {
        // write object to file
        FileOutputStream fos = new FileOutputStream("ConeOutput1.txt", true);
        BufferedOutputStream outputBuffer = new BufferedOutputStream(fos);
        AppendableObjectOutputStream objectStream = new AppendableObjectOutputStream(outputBuffer);
        objectStream.writeObject(m);
        objectStream.reset();
        objectStream.close();
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
}

public Memento getMemento(String temp) {
    try {
    Memento result = null;
    FileInputStream fis = new FileInputStream("ConeOutput1.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);
    result = (Memento) ois.readObject();
    while (result != null) {
        Matcher m = Pattern.compile(temp).matcher(result.toString());
        if (m.find()) {
            return result;
        }
        else {
            result = (Memento) ois.readObject();
        }
        ois.close();
    }
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

}

代码语言:javascript
复制
public class AppendableObjectOutputStream extends ObjectOutputStream {
  public AppendableObjectOutputStream(OutputStream out) throws IOException {
    super(out);
  }

  @Override
  protected void writeStreamHeader() throws IOException {}

}

EN

回答 1

Stack Overflow用户

发布于 2017-10-24 04:20:01

仅当文件中已存在包含数据的文件时,才应使用附加ObjectOutputStream。如果文件是新的,则需要对象流头。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46897582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档