每次运行程序时,我想序列化文件上的同一对象。这是一个解释我的问题的简单算法。
一开始我存储了一个String
上writer
。最后我读了一个文件。
该程序的目标是,如果我运行我的程序 X 次,我会存储并在屏幕上打印我的对象 X 次。
class ReadFile {
static ObjectOutputStream writer = null;
public static void main(String[] args) throws IOException, ClassNotFoundException {
writer = new ObjectOutputStream(new FileOutputStream("trace", true));
store("String");
if (writer != null) {
writer.close();
}
open("file.tmp");
}
static public void store(String chaine) {
if (writer == null) {
return;
}
try {
writer.writeObject(chaine);
} catch (IOException ex) {
}
}
static public void open(String file) throws FileNotFoundException, IOException, ClassNotFoundException {
StringBuilder str = new StringBuilder();
ObjectInputStream objs;
try {
objs = new ObjectInputStream(new FileInputStream(file));
try {
while (true) {
Object obj = objs.readObject();
str.append(obj.toString());
}
} catch (EOFException ex) {
}
objs.close();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
}
当我运行这个程序时,我遇到了这个错误:
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at ReadFile.open(ReadFile.java:47)
at ReadFile.main(ReadFile.java:35)
请问我能做什么?
最佳答案
根据this发布后,您无法追加到 ObjectOutputStream,您尝试通过以追加模式打开底层 FileOutputStream 来实现这一点。该帖子提到了一个解决方案,您可以创建一个 AppendableObjectOutputStream ,或者您可以只打开 FileOutputStream 而不附加。
关于java - 异常 StreamCorruptedException : invalid type code: AC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13234475/