Java Reference
In-Depth Information
This class defines an output stream to which you can write
any of the basic types of data.
DataOutputStream
This class defines an output stream to which you can write
any class of object. The physical file is specified by passing a
object to the constructor. You write
ObjectOutputStream
FileOutputStream
writeObject()
objects by using the
method.
This class defines an input stream from which you can read any
of the basic types of data.
DataInputStream
This class defines an input stream from which you can read
objects. The physical file is specified by passing a
object to the constructor. You read objects
ObjectInputStream
FileInputStream
readObject()
by using the
method.
Two classes from the java.io package are used for serialization. An ObjectOutputStream object
manages the writing of objects to a file, and reading the objects back is handled by an object of the class
ObjectInputStream . As we saw in Chapter 8, these are derived from OutputStream and
InputStream , respectively.
Writing an Object to a File
The constructor for the ObjectOutputStream class requires a reference to a FileOutputStream
object as an argument that defines the stream for the file where you intend to store your objects. You
could create an ObjectOutputStream object with the following statements:
File theFile = new File("MyFile");
// Check out the file...
// Create the object output stream for the file
ObjectOutputStream objectOut = null;
try {
objectOut = new ObjectOutputStream(new FileOutputStream(theFile));
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
We know from our earlier investigations into file input that the FileOutputStream constructor can
throw a FileNotFoundException if the File object that you pass to the constructor represents a
directory rather than a file, or if the file does not exist and cannot be created for some reason. In
addition the ObjectOutputStream constructor will throw an IOException if an error occurs while
the stream header is written to the file. Our catch block here will handle either of these exceptions.
Search WWH ::




Custom Search