Java Reference
In-Depth Information
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
.
Display 10.17
Using
EOFException
(part 1 of 2)
1
import
java.io.ObjectInputStream;
2
import
java.io.FileInputStream;
3
import
java.io.EOFException;
4
import
java.io.IOException;
5
import
java.io.FileNotFoundException;
6
public class
EOFDemo
7 {
8
public static void
main(String[] args)
9 {
10
try
11 {
12 ObjectInputStream inputStream =
13
new
ObjectInputStream(
new
FileInputStream("numbers.dat"));
14
int
number;
15 System.out.println("Reading numbers in numbers.dat");
16
try
17 {
18
while
(
true
)
19 {
20 number = inputStream.readInt( );
21 System.out.println(number);
22 }
23 }