How to append to an ObjectInputStream without getting java.io.StreamCorruptedException: invalid type code: AC?

(I am appending to the file during the writing phase)

And that is the problem. You can't append to an ObjectOutputStream. That will definitly corrupt the stream and you get StreamCorruptedException.

But I already left a solution to this problem on SO: an AppendableObjectOutputStream

EDIT

From the writer I see that you write one cheque object and flush and close the stream. From the reader, I clearly see, that you're trying to read more than one cheque object. And you can read the first one but not the rest. So to me it is perfectly clear, that you reopen the Stream and append more and more cheque objects. Which is not allowed.

You have to write all cheque objects in 'one session'. Or use the AppendableObjectOutputStream instead of the standard ObjectOutputStream.


Creating a new ObjectInputStream without closing the underlying FileInputStream solves this problem:

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

Tags:

Java

File Io