Programming and Problem Solving with Java

(やまだぃちぅ) #1
7.8 Output and Input of Objects | 357

Here is infile.dat:

The application that reads the object back in and prints it is very straightforward. We ap-
ply readObjectto the file of type ObjectInputStream, which returns an object of the class Object.
Note that the object read from the file must be cast into a Nameobject before being assigned
to the personvariable. We use the methods of the class Nameto access the fields so as to print
them. We must also mention one more piece of syntax: readObjectcan throw a
ClassNotFoundException. In Chapter 9, we show how to handle an exception, but for the mo-
ment we just add it to the throwsclause of the mainmethod.


importjava.io.*;
importName;


public classObjectFileRead
{
public static void main(String[] args)
throwsIOException, ClassNotFoundException
{
ObjectInputStream inObject; //Input file
Name person;
// Prepare file
inObject = new ObjectInputStream(new FileInputStream("outObject.dat"));


//Read Name object
person = (Name)inObject.readObject();

System.out.println(person.knowFirstName() + ' ' +
person.knowMiddleName() + ' ' + person.knowLastName());
inObject.close();
}
}

Free download pdf