Java Reference
In-Depth Information
file , as the argument creates an input stream for the file. This is exactly as you saw in Chapter 11. As you
know, the default open option that is assumed is READ .
After you have created the ObjectInputStream object, you call its readObject() method to read an
object from the file:
try (ObjectInputStream objectIn =
new ObjectInputStream(new BufferedInputStream(Files.newInputStream(file)))){
Object myObject = objectIn.readObject();
} catch(ClassNotFoundException|IOException e){
e.printStackTrace();
}
The readObject() method can throw the following exceptions:
ClassNotFoundException : Thrown if the class for an object read from the stream cannot be
found.
InvalidClassException : Thrown if something is wrong with the class for an object. Often this
is caused by using a class definition when you read an object from a stream that is different from
the class definition in effect when you wrote it.
StreamCorruptedException : When objects are written to the stream, additional control data is
written so that the object data can be validated when it is read back. This exception is thrown when
the control information in the stream violates consistency checks.
OptionalDataException : Thrown when basic types of data are read rather than an object. For
example, if you wrote a String object using the writeChars() method and then attempted to
read it back using the readObject() method, this exception would be thrown.
EOFException : Thrown if the end-of-file is read.
IOException : Thrown if an error occurred reading the stream.
Clearly, if you do not have a full and accurate class definition for each type of object that you want to
read from the stream, the stream object does not know how to create the object and the read fails. The last
five of the six possible exceptions are flavors of IOException , so you can use that as a catchall as you have
in the preceding code fragment. However, ClassNotFoundException is derived from Exception , so you
must provide for catching this exception, too. Otherwise, the code does not compile. Here, you catch either
exception type in the same catch block because you have the same action for both.
As the code fragment implies, the readObject() method returns a reference to the object as type Object ,
so you need to cast it to the appropriate class type to use it. Note that arrays are considered to be objects and
are treated as such during serialization, so if you explicitly read an array from a file, you have to cast it to
the appropriate array type.
For example, if the object in the previous code fragment was of type MyClass , you could read it back
from the file with the statement:
MyClass theObject = (MyClass)(objectIn.readObject());
This casts the reference that is returned by the readObject() method to type MyClass .
Armed with the knowledge of how the readObject() method works, you can now read the file that you
wrote in the previous example.
Search WWH ::




Custom Search