ObjectInput
TheObjectInputinterface extends theDataInputinterface and defines the methods shown
in Table 19-8. It supports object serialization. Note especially thereadObject( )method. This
is called to deserialize an object. All of these methods will throw anIOExceptionon error
conditions. ThereadObject( )method can also throwClassNotFoundException.
ObjectInputStream
TheObjectInputStreamclass extends theInputStreamclass and implements theObjectInput
interface.ObjectInputStreamis responsible for reading objects from a stream. A constructor of
this class is
ObjectInputStream(InputStreaminStream)
throws IOException
The argumentinStreamis the input stream from which serialized objects should be read.
Several commonly used methods in this class are shown in Table 19-9. They will
throw anIOExceptionon error conditions. ThereadObject( )method can also throw
ClassNotFoundException. There is also an inner class toObjectInputStreamcalledGetField.
It facilitates the reading of persistent fields, and its use is beyond the scope of this book.
A Serialization Example
The following program illustrates how to use object serialization and deserialization. It begins
by instantiating an object of classMyClass. This object has three instance variables that are of
typesString,int, anddouble. This is the information we want to save and restore.
Chapter 19: Input/Output: Exploring java.io 595
Method Description
int available( ) Returns the number of bytes that are now available in the
input buffer.
void close( ) Closes the invoking stream. Further read attempts will
generate anIOException.
int read( ) Returns an integer representation of the next available byte
of input. –1 is returned when the end of the file is
encountered.
int read(bytebuffer[ ]) Attempts to read up tobuffer.lengthbytes intobuffer,
returning the number of bytes that were successfully read.
–1 is returned when the end of the file is encountered.
int read(bytebuffer[ ], intoffset,
intnumBytes)
Attempts to read up tonumBytesbytes intobufferstarting
atbuffer[offset], returning the number of bytes that were
successfully read. –1 is returned when the end of the file is
encountered.
Object readObject( ) Reads an object from the invoking stream.
long skip(longnumBytes) Ignores (that is, skips)numBytesbytes in the invoking
stream, returning the number of bytes actually ignored.
TABLE 19-8 The Methods Defined byObjectInput