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 anOutputStream
, in this case aFileOutputStream
, is needed to receive the bytes. Then anObjectOutputStream
is created that writes to theFileOutputStream
. Next, the string "Today" and a Date object are written to the stream. More generally, objects are written with thewriteObject
method and primitives are written to the stream with the methods ofDataOutput
.The
writeObject
method (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
Class
,ObjectStreamClass
,String
, and arrays. Other objects must implement either theSerializable
or theExternalizable
interface to be saved in or restored from a stream.Primitive data types are written to the stream with the methods in the
DataOutput
interface, such aswriteInt
,writeFloat
, orwriteUTF
. Individual bytes and arrays of bytes are written with the methods ofOutputStream
. 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.
ObjectOutputStream
can be extended to customize the information about classes in the stream or to replace objects to be serialized. Refer to theannotateClass
andreplaceObject
method descriptions for details.