Java Reference
In-Depth Information
Display 10.17
Using EOFException
(part 2 of 2)
Sample Dialogue
Reading numbers in numbers.dat
0
1
2
3
4
No more numbers in the file.
Assumes the program in
Display 10.13 was run to
create the file
numbers.dat
.
We will discuss interfaces in general in Chapter 13. However, the
Serializable
interface is particularly easy to use and requires no knowledge of interfaces. All you
need to do to make a class implement the
Serializable
interface is add the two words
implements
Serializable
to the heading of the class definition, as in the following
example:
Serial-izable
interface
public class
Person
implements
Serializable
{
The
Serializable
interface is in the same
java.io
package that contains all the I/O
classes we have discussed in this chapter. For example, in Display 10.18 we define a toy
class named
SomeClass
that implements the
Serializable
interface. We will explain the
effect of the
Serializable
interface a bit later in this chapter, but first let's see how you
do binary file I/O with a serializable class such as this class
SomeClass
in Display 10.18.
Display 10.19 illustrates how class objects can be written to and read from a binary
file. To write an object of a class such as
SomeClass
to a binary file, you simply use the
method
writeObject
of the class
ObjectOutputStream
. You use
writeObject
in the
same way that you use the other methods of the class
ObjectOutputStream
, such as
writeInt
, but you use an object as the argument.
If an object is written to a file with
writeObject
, then it can be read back out of the
file with
readObject
of the stream class
ObjectInputStream
, as also illustrated in Dis-
play 10.19. The method
readObject
returns its value as an object of type
Object
. If
you want to use the values retuned by
readObject
as an object of a class like
Some-
Class
, you must do a type cast, as shown in Display 10.19.
writeObject
readObject
The
Serializable
Interface
A class that implements the
Serializable
interface is said to be a
serializable
class. To
use objects of a class with
writeObject
and
readObject
, that class must be serializable.
But to make the class serializable, we change nothing in the class. All we do is add the
phrase
implements
Serializable
. This phrase tells the run-time system that it is OK
to treat objects of the class in a particular way when doing file I/O. If a class is serializ-
able, Java assigns a serial number to each object of the class that it writes to a stream of
serializable