我有一个利用memento设计模式的程序,希望使用序列化将每个对象的状态保存到一个文件中,并返回该对象。问题是我得到了一个"java.io.StreamCorruptedException: invalid type code: AC“异常,因为报头损坏。我查看了Appending to an ObjectOutputStream并尝试实现该类,但仍然无法使程序正常工作。多个对象应该保存在一个文件中,并且用户将一个字符串传递给一个函数,该函数应该与对象的字符串表示的一部分相匹配。
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;
}}
public class AppendableObjectOutputStream extends ObjectOutputStream {
public AppendableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {}}
发布于 2017-10-24 04:20:01
仅当文件中已存在包含数据的文件时,才应使用附加ObjectOutputStream。如果文件是新的,则需要对象流头。
https://stackoverflow.com/questions/46897582
复制相似问题