CONTENTS | PREV | NEXT | Java Object Serialization Specification |
Reading an object from a stream, like writing, is straightforward:// Deserialize a string and date from a file. FileInputStream in = new FileInputStream("tmp"); ObjectInputStream s = new ObjectInputStream(in); String today = (String)s.readObject(); Date date = (Date)s.readObject();First anInputStream
, in this case aFileInputStream
, is needed as the source stream. Then anObjectInputStream
is created that reads from theInputStream
. Next, the string "Today" and a Date object are read from the stream. Generally, objects are read with thereadObject
method and primitives are read from the stream with the methods ofDataInput
.The
readObject
method deserializes the next object in the stream and traverses its references to other objects recursively to create the complete graph of objects serialized.Primitive data types are read from the stream with the methods in the
DataInput
interface, such asreadInt
,readFloat
, orreadUTF
. Individual bytes and arrays of bytes are read with the methods ofInputStream
. Except for serializable fields, primitive data is read from block-data records.
ObjectInputStream
can be extended to utilize customized information in the stream about classes or to replace objects that have been deserialized. Refer to theresolveClass
andresolveObject
method descriptions for details.