java.io.StreamCorruptedException:类型代码无效:AC

我试图从文件中读取一些对象。 代码在第一次迭代时工作正常,在第二次迭代时,它产生StreamCorruptedException。 这是我的代码,

private ArrayList cheques = null; ObjectInputStream ois = null; try { cheques = new ArrayList(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) 

我无法弄清楚为什么会这样。 在一些论坛post中,我发现在写入文件时附加到文件时会发生这种情况。 这是真正的原因吗? (我在写作阶段附加到文件中)。 如果有,是否有正确的方法来读取附加文件?

这是我用来写入文件的代码

  ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("src\\easycheque\\data\\templates.dat", true)); objectOut.writeObject(cheque); objectOut.flush(); objectOut.close(); 

写作不是一个迭代过程。

谢谢 :)

(我在写作阶段附加到文件中)

这就是问题所在。 您无法附加到ObjectOutputStream。 这肯定会破坏流,你会得到StreamCorruptedException。

但是我已经在SO上留下了这个问题的解决方案:一个AppendableObjectOutputStream

编辑

从编写器中我看到你写了一个检查对象并刷新并关闭流。 从读者,我清楚地看到,你正在尝试阅读多个检查对象。 你可以阅读第一个而不是其他的。 所以对我来说非常清楚,你重新打开Stream并附加越来越多的检查对象。 这是不允许的。

您必须在“一个会话”中编写所有检查对象。 或者使用AppendableObjectOutputStream而不是标准的ObjectOutputStream。

在不关闭底层FileInputStream的情况下创建新的ObjectInputStream可以解决此问题:

  FileInputStream fin = new FileInputStream(file); while (...) { ObjectInputStream oin = new ObjectInputStream(fin); Object o = oin.readObject(); ... } fin.close();