Java Reference
In-Depth Information
header, and java.io.StreamCorruptedException (an indirect subclass of
IOException ) when the stream header is incorrect.
ObjectInputStream deserializes an object via its readObject() method.
Thismethodattemptstoreadinformationabout obj 'sclassfollowedbythevaluesof
obj 's instance fields from the underlying input stream.
readObject() throws java.lang.ClassNotFoundException , IOEx-
ception ,oraninstanceofan IOException subclasswhensomethinggoeswrong.
For example, this method throws java.io.OptionalDataException when it
encounters primitive values instead of objects.
Note Because ObjectInputStream implements DataInput ,it also declares
methods for reading primitive type values and strings from an object input stream.
Listing8-15 presentsanapplicationthatusestheseclassestoserializeanddeserialize
an instance of Listing 8-14 's Employee class to and from an employee.dat file.
Listing 8-15. Serializing and deserializing an Employee object
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class SerializationDemo
{
final static String FILENAME = "employee.dat";
public static void main(String[] args)
{
try (ObjectOutputStream oos =
new
ObjectOutputStream(new
FileOut-
putStream(FILENAME)))
{
Employee emp = new Employee("john doe", 36);
oos.writeObject(emp);
}
catch (IOException ioe)
{
 
Search WWH ::




Custom Search