Java Reference
In-Depth Information
The writeObject() method can throw any of the following three exceptions:
InvalidClassException
Thrown when there is something wrong with the
class definition for the object being written. This
might be because the class is not public , for
instance.
NotSerializableException
Thrown if the object's class, or the class of a data
member of the class, does not implement the
Serializable interface.
IOException
Thrown when a file output error occurs.
The first two exception classes here are subclasses of ObjectStreamException , which is itself a
subclass of IOException . Thus we can catch any of them with a catch block for IOException . Of
course, if you want to take some specific action for any of these then you can catch them individually.
Just be sure to put the catch blocks for the first two types of exception before the one for
IOException .
The call to writeObject() takes care of writing everything to the stream that is necessary to
reconstitute the object later in a read operation. This includes information about the class and all its
superclasses, as well as the contents and types of the data members of the class. Remarkably, this works
even when the data members are themselves class objects, as long as they are objects of
Serializable classes. Our writeObject() call will cause the writeObject() method for each
object that is a data member to be called, and this mechanism continues recursively until everything
that makes up our object has been written to the stream. Each independent object that you write to the
stream requires a separate call to the writeObject() method, but the objects that are members of an
object are taken care of automatically. This is not completely foolproof in that the relationships between
the class objects can affect this process, but for the most part this is all you need to do. We will be using
serialization to write fairly complex objects to files in Chapter 20.
Writing Basic Data Types to an Object Stream
You can write data of any of the primitive types using the methods defined in the
ObjectOutputStream class for this purpose. For writing individual items of data of various types,
you have the following methods:
writeByte(int b)
writeByte(byte b)
writeChar(int ch)
writeShort(int n)
writeInt(int n)
writeLong(long n)
writeFloat(
float x)
writeDouble(
double x)
None of them return a value and they can all throw an IOException since they are output operations.
Search WWH ::




Custom Search