Java Reference
In-Depth Information
An object input stream is created with the ObjectInputStream( InputStream )
constructor. Two exceptions are thrown by this constructor: IOException and
StreamCorruptionException . IOException , common to stream classes, occurs
whenever any kind of input/output error occurs during the data transfer.
StreamCorruptionException is specific to object streams, and it indicates that the data
in the stream is not a serialized object.
An object input stream can be constructed from an input stream or a filtered stream.
The following code creates an input stream and an object input stream to go along
with it:
16
try {
FileInputStream disk = new FileInputStream(
“SavedObject.dat”);
ObjectInputStream obj = new ObjectInputStream(disk);
} catch (IOException ie) {
System.out.println(“IO error -- “ + ie.toString());
} catch (StreamCorruptionException se) {
System.out.println(“Error - data not an object.”);
}
This object input stream is set up to read from an object stored in a file called SavedObject.
dat . If the file does not exist or cannot be read from disk for some reason, an IOException
is thrown. If the file isn't a serialized object, a thrown StreamCorruptionException indi-
cates this problem.
An object can be read from an object input stream by using the readObject() method,
which returns an Object . This object can be immediately cast into the class to which it
belongs, as in the following example:
WorkData dd = (WorkData)disk.readObject();
This statement reads an object from the disk object stream and casts it into an
object of the class WorkData . In addition to IOException , this method throws
OptionalDataException and ClassNotFoundException errors.
OptionalDataException indicates that the stream contains data other than serialized
object data, which makes it impossible to read an object from the stream.
ClassNotFoundException occurs when the object retrieved from the stream belongs to a
class that could not be found. When objects are serialized, the class is not saved to the
stream. Instead, the name of the class is saved to the stream, and the class is loaded by
the Java interpreter when the object is loaded from a stream.
Search WWH ::




Custom Search