This question already has an answer here:
- Appending to an ObjectOutputStream 5 answers
As for now I will get java.io.StreamCorruptedException
when I try to append an Object. I have searched the Internet for a way to overcome that. The answer I found so far is it can't be done. A way around this problem is to write the objects into a list and then write the list to the file.
But I have to overwrite that file everytime when I add new objects. It seems not to be the optimal solution in overtime.
Is there a way to append objects to an existing object stream?
The best article I've found on this topic is: http://codify.flansite.com/2009/11/java-serialization-appending-objects-to-an-existing-file/
The "solution" that overrides ObjectOutputStream is simply wrong. I've just finished investigating a bug that was caused by that (wasting two precious days). Not only that it would sometimes corrupt the serialized file but even managed to read without throwing exceptions and in the end providing garbage data (mixing fields). For those in disbelief, I'm attaching some code that exposes the problem:
As stated in that article, you can use one of the following solutions:
Many thanks to George Hategan for the problem exposing code. I examined it for a while too. Then, it hit me. If you're using a sub-classed ObjectOutputStream with an override of the writeStreamHeader() method to write data, you must use the parallel sub-classed ObjectInputStream with an override of the readStreamHeader() method to read the data. Of course, we can zig-zag between different implementations of writing and reading objects, but as long as we use the corresponding pairs of sub-classes in the write/read process - we'll be (hopefully) fine. Tom.
It is actually pretty easy to do. When you are adding to an existing stream you need to use a subclass of ObjectOutStream that overrides
writeStreamHeader
so that a second header is not written in the middle of the file. For exampleThen just use a standard ObjectInputStream to read the whole file.
You would need to create a new
ObjectInputStream
to match everyObjectOutputStream
. I don't know a way to transfer state from a completeObjectInputStream
to anObjectOutputStream
(without a complete reimplementation, which is a bit tricky in pure Java anyway).