Java Reference
In-Depth Information
Name: John, Gender: Male, Height: 6.7
Name: Wally, Gender: Male, Height: 5.7
Name: Katrina, Gender: Female, Height: 5.4
Objects were written to C:\book\javabook\person.ser
Deserializing Objects
It is time to read the objects back from the
person.ser
file. Reading a serialized object is just the opposite of
serializing it. To deserialize an object, you need to perform the following steps:
•
Create an object input stream for the storage medium from which objects will be read.
•
Read the objects.
•
Create an object of the
ObjectInputStream
class by using it as a decorator for another input stream that
represents the storage medium where serialized objects are stored. For example, to read an object from a
person.ser
file, create an object input stream as follows:
Close the object input stream.
// Create an object input stream to read objects from a file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"));
To read objects from a
ByteArrayInputStream
, create an object output stream as follows:
// Create an obejct input stream to read obejcts from a byte array input stream
ObjectInputStream ois = new ObjectInputStream(Byte-Array-Input-Stream-Reference);
Use the
readObject()
method of the
ObjectInputStream
class to deserialize the object, like so:
// Read an object from the stream
Object obj = oos.readObject();
Make sure to call the
readObject()
method to read objects in the same order you called the
writeObject()
method to write objects. For example, if you wrote three pieces of information in the order
object-1
, a
float
, and
object-2
, you must read them in the same order:
object-1
, a
float
, and
object-2
.
Finally, close the object input stream as follows:
// Close the object input stream
ois.close();
Listing 7-25 demonstrates how to read objects from the
person.ser
file. Make sure that the
person.ser
file exists
in your current directory. Otherwise, the program will print an error message with the expected location of this file.
Listing 7-25.
Reading Objects from a File
// PersonDeserializationTest.java
package com.jdojo.io;
import java.io.File;
import java.io.FileInputStream;