Java Reference
In-Depth Information
Display 10.16
Reading from a Binary File (part 2 of 2)
21
catch (FileNotFoundException e)
22
{
23
System.out.println("Cannot find file numbers.dat.");
24
}
25
catch (IOException e)
26
{
27
System.out.println("Problems with input from numbers.dat.");
28
}
29
System.out.println("End of program.");
30
}
31
}
Sample Dialogue
Reading the file numbers.dat.
Numbers read from file:
0
1
End of program.
Assumes the program in
Display 10.13 was run to create
the file numbers.dat .
Checking for the End of a Binary File
All of the ObjectInputStream methods that read from a binary file will throw an
EOFException when they try to read beyond the end of a file. So your code can test for
the end of a binary file by catching an EOFException as illustrated in Display 10.17.
In Display 10.17, the reading is placed in an “infinite loop” through the use of true
as the Boolean expression in the while loop. The loop is not really infinite, because
when the end of the file is reached, an exception is thrown, and that ends the entire
try block and passes control to the catch block.
EOF-
Exception
EOFException
If your program is reading from a binary file using any of the methods listed in Display 10.15 for
the class ObjectInputStream , and your program attempts to read beyond the end of the file,
then an EOFException is thrown. This can be used to end a loop that reads all the data in a file.
The class EOFException is a derived class of the class IOException . So, every exception of
type EOFException is also of type IOException .
 
Search WWH ::




Custom Search