Java Reference
In-Depth Information
PITFALL: Checking for the End of a File in the Wrong Way
Different file-reading methods check for the end of a file in different ways. If you test
for the end of a file in the wrong way, one of two things will probably happen: Your
program will either go into an unintended infinite loop or terminate abnormally.
For the classes discussed in this topic, the following rules apply: If your program is
reading from a binary file, then an EOFException will be thrown when the reading goes
beyond the end of the file. If your program is reading from a text file, then no
EOFException will be thrown when reading goes beyond the end of the file.
Self-Test Exercises
37. When opening a binary file for output in the ways discussed in this chapter,
might an exception be thrown? What kind of exception? When opening a binary
file for input in the ways discussed in this chapter, might an exception be
thrown? What kind of exception?
38. Suppose a binary file contains three numbers written to the file with the method
writeDouble of the class ObjectOutputStream . Suppose further that your pro-
gram 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 num-
ber? 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 infinite 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.
Search WWH ::




Custom Search