|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 an
InputStream, in this case a
FileInputStream, is needed as the source stream. Then an
ObjectInputStreamis created that reads from the
InputStream. Next, the string "Today" and a Date object are read from the stream. Generally, objects are read with the
readObjectmethod and primitives are read from the stream with the methods of
readObjectmethod 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
DataInputinterface, such as
readUTF. Individual bytes and arrays of bytes are read with the methods of
InputStream. Except for serializable fields, primitive data is read from block-data records.
ObjectInputStreamcan be extended to utilize customized information in the stream about classes or to replace objects that have been deserialized. Refer to the
resolveObjectmethod descriptions for details.