Note that there are some explanatory texts on larger screens.

plurals
  1. POjava.io.StreamCorruptedException: invalid type code: AC
    text
    copied!<p>I am trying to read some objects from a file. The code works fine for the first iteration and at the second iteration it gives a StreamCorruptedException. Here is my code,</p> <pre><code>private ArrayList&lt;Cheque&gt; cheques = null; ObjectInputStream ois = null; try { cheques = new ArrayList&lt;Cheque&gt;(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); } </code></pre> <p>below is part of the exception. Before printing this '1' is printed (because of the sout)</p> <pre><code>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) </code></pre> <p>I can't figure out why this is happening. In few forum posts, I came across that this happens when you append to a file during writing it. Is it the real reason?. (I am appending to the file during writing phase). If so is there a proper way to read an appended file? </p> <p>here is the code i use to write to the file</p> <pre><code> ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("src\\easycheque\\data\\templates.dat", true)); objectOut.writeObject(cheque); objectOut.flush(); objectOut.close(); </code></pre> <p>writing is not an iterative process.</p> <p>Thank you :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload