每次运行程序时,我都想序列化文件中的相同对象。这是一个简单的算法来解释我的问题。
在开始时,我将 a 存储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)
请问我该怎么办?