|CONTENTS | PREV | NEXT||Java Object Serialization Specification|
Writing objects and primitives to a stream is a straightforward process. For example:
// Serialize today's date to a file. FileOutputStream f = new FileOutputStream("tmp"); ObjectOutput s = new ObjectOutputStream(f); s.writeObject("Today"); s.writeObject(new Date()); s.flush();First an
OutputStream, in this case a
FileOutputStream, is needed to receive the bytes. Then an
ObjectOutputStreamis created that writes to the
FileOutputStream. Next, the string "Today" and a Date object are written to the stream. More generally, objects are written with the
writeObjectmethod and primitives are written to the stream with the methods of
writeObjectmethod (see Section 2.3, "The writeObject Method") serializes the specified object and traverses its references to other objects in the object graph recursively to create a complete serialized representation of the graph. Within a stream, the first reference to any object results in the object being serialized or externalized and the assignment of a handle for that object. Subsequent references to that object are encoded as the handle. Using object handles preserves sharing and circular references that occur naturally in object graphs. Subsequent references to an object use only the handle allowing a very compact representation.
Special handling is required for objects of type
String, and arrays. Other objects must implement either the
Externalizableinterface to be saved in or restored from a stream.
Primitive data types are written to the stream with the methods in the
DataOutputinterface, such as
writeUTF. Individual bytes and arrays of bytes are written with the methods of
OutputStream. Except for serializable fields, primitive data is written to the stream in block-data records, with each record prefixed by a marker and an indication of the number of bytes in the record.
ObjectOutputStreamcan be extended to customize the information about classes in the stream or to replace objects to be serialized. Refer to the
replaceObjectmethod descriptions for details.