Is it possible to deserializable object from a file and then serializable only few of them into the same file? Of course numbers of object before and after must be the same. I don't want to add new objects into file, but overwrite changed objects. For example there are about 1000 objects which I get from file 'file.ser'. I deserializable them, change only 3 and want to overwrite these into same file. Is it possible?
The short answer is no, you cannot just overwrite the changed objects "in-place" within the file.
When you create an
ObjectOutputStream, even before you write an object into it, the stream writes some magic number marker bytes to the underlying stream. These bytes are automatically consumed by an
ObjectInputStream when you create one. This is the stream header.
Furthermore, when you write an object using
ObjectOutputStream.writeObject(), you're not simply serialisaing that object is isolation. The stream keeps track of objects references that it has serialised previously (unless you call
reset()), and instead of writing the object out in full, it will write a handle that points back to where the real object was written.
Finally, there is no block alignment or padding between the objects written to the stream -- they're written contiguously.
All of this means that if you change an object, the structural changes you've made (references to different objects etc) means that the handles could be different, and the length of the object could be different. Since there's no block alignment occurring, you can't write the object back to the same place because the changes you've made will (likely) affect the length and it won't be the same, which means you'll stomp over the top of another object.
No, you have to recreate the file. The object stream is indeed a stream, not just a set of records.
If you are concerned about speed, I've always found Java to be pretty fast. There might not be too much penalty in reading the whole thing - try some profiling.
You could try replacing Java Serialization with an alternative such as Google Protocol Buffers.
ProtoBuf is very quick and very space efficient.