我想从文件读取一些对象。该代码在第一次迭代中工作正常,在第二次迭代中,它给出了StreamCorruptedException。这里是我的代码,java.io.StreamCorruptedException:无效的类型代码:AC
private ArrayList<Cheque> cheques = null;
ObjectInputStream ois = null;
try {
cheques = new ArrayList<Cheque>(4);
ois = new ObjectInputStream(new FileInputStream("src\\easycheque\\data\\Templates.dat"));
Object o = null;
try {
o = ois.readObject();
int i=1;
while (o != null) {
cheques.add((Cheque) o);
System.out.println(i++); // prints the number of the iteration
o = ois.readObject(); // exception occurs here
}
} catch (ClassNotFoundException ex) {// for ois readObject()
Logger.getLogger(TemplateReader.class.getName()).log(Level.SEVERE, null, ex);
} catch (EOFException ex) {// for ois readObject()
// end of the file reached stop reading
System.out.println("ois closed");
ois.close();
}
} catch (IOException ex) {
Logger.getLogger(TemplateReader.class.getName()).log(Level.SEVERE, null, ex);
}
下面是例外的一部分。在打印之前,打印出'1'(因为是sout)
SEVERE: null
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1356)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
我不明白为什么会发生这种情况。在少数论坛帖子中,我发现在编写文件的过程中追加到文件时会发生这种情况。这是真正的原因吗? (我在写作阶段追加到文件中)。 如果有,是否有正确的方法来读取附加文件?
这里是代码我使用写入文件
ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("src\\easycheque\\data\\templates.dat", true));
objectOut.writeObject(cheque);
objectOut.flush();
objectOut.close();
写作不是一个反复的过程。
谢谢:)
你可以添加写入文件以及示例代码片段? – 2010-07-05 21:28:57
可以改变对象的大小吗?我正在写的每个对象都有一个图像对象(Icon) – Niroshan 2010-07-05 21:51:39
直到readObject()返回null时才循环是不正确的。它不会在流结束时执行该操作,并且可以在您编写空值的任何其他时间执行此操作。您需要循环,直到抛出“EOFException”。 – EJP 2016-02-21 21:13:37