Java Reference
In-Depth Information
Display 10.17
Using EOFException (part 2 of 2)
24 catch (EOFException e)
25 {
26 System.out.println("No more numbers in the file.");
27 }
28 inputStream.close();
29 }
30 catch (FileNotFoundException e)
31 {
32 System.out.println("Cannot find file numbers.dat.");
33 }
34 catch (IOException e)
35 {
36
System.out.println("Problem with input from file
numbers.dat.");
37 }
38 }
39 }
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 .
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 it will terminate
abnormally.
For the classes discussed in this topic , the following rules apply: If your program
is reading from a binary fi le, then an EOFException will be thrown when the read-
ing goes beyond the end of the fi le. If your program is reading from a text fi le, then
no EOFException will be thrown when reading goes beyond the end of the fi le.
 
 
Search WWH ::




Custom Search