How can I modify a serialized object which is stored in a file if the file contains a large number of objects?

Doug Bell

The short answer is that you probably can't without deserializing the objects and reserializing and rewriting the objects.

The serialized format is truly a stream-oriented protocol and does not support random access--it is both self-referential and incremental. When an object is written to the stream, a description of the class and its non-static and non-transient fields (including any Serializable superclasses and their non-static and non-transient fields) is also written to the steam. Then the entire object graph of non-transient fields of Serializable classes is written, which means that non-null object references to serializable objects are recursively serialized. Throughout this process, object identity is maintained by adding object handles to a table maintained by both ObjectOutputStream and ObjectInputStream. When an object previously encountered in the stream is serialized, only the object handle is written to the stream. Object handles are used to maintain identity for not only objects, but also the class descriptions and even the strings used for class and field names.

So even if you had the offset within the stream of the object you want to modify, without having processed all of the preceeding content it is unlikely that all the data needed to interpret the serialized data for the object would be present.

Note that the reset() method of ObjectOutputStream can be used during serialization to reset the table of object handles. This may allow you to devise a means of serializing your objects in a more localized manner. However, resetting the stream means that any previously written objects will be serialized as separate objects, and consequently, deserialized as separate objects. In other words, object references that previosuly referred to the same object will refer to different objects after deserialization.

About | Sitemap | Contact