Java Reference
In-Depth Information
Self-Test Exercises
37.
When opening a binary fi le for output in the ways discussed in this chapter,
might an exception be thrown? What kind of exception? When opening a
binary fi le for input in the ways discussed in this chapter, might an exception be
thrown? What kind of exception?
38.
Suppose a binary fi le contains three numbers written to the fi le with the
method
writeDouble
of the class
ObjectOutputStream
. Suppose further that
your program reads all three numbers with three invocations of the method
readDouble
of the class
ObjectInputStream
. When will an
EOFException
be thrown? Right after reading the third number? When your program tries to
read a fourth number? Some other time?
39.
The following appears in the program in Display 10.17 :
try
{
while
(
true
)
{
number = inputStream.readInt();
System.out.println(number);
}
}
catch
(EOFException e)
{
System.out.println("No more numbers in the file.");
}
Why isn't this an infi nite loop?
Binary I/O of Objects
You can output objects of classes you define as easily as you output
int
values using
writeInt
, and you can later read the objects back into your program as easily as you read
int
values with the method
readInt
. For you to be able to do this, the class of objects
that your code is writing and reading must implement the
Serializable
interface.
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:
Serializable
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