Java Reference
In-Depth Information
Self-Test Exercises
(continued)
15. One difference between the
try
blocks in Display 10.1 and Display 10.7 is
that the
try
block in Display 10.1 encloses only the opening of the fi le, while
the
try
block in Display 10.7 encloses most of the action in the program. Why
is the
try
block in Display 10.7 larger than the one in Display 10.1 ?
16. Might the following throw an exception that needs to be caught or declared in
a
throws
clause?
BufferedReader inputStream =
new
BufferedReader(
new
FileReader("morestuff2.txt"));
(The stream
inputStream
would be used to read from the text fi le
morestuff2.txt
.)
TIP: Reading Numbers with
BufferedReader
Unlike the
Scanner
class, the class
BufferedReader
has no methods to read a
number from a text file. You must write your code to read the number as a string
and convert the string to a value of a numeric type, such as
int
or
double
. To read
a single number on a line by itself, read it using the method
readLine
, and then use
Integer.parseInt
,
Double.parseDouble
, or some similar method to convert the
string read to a number. If there are multiple numbers on a single line, read the line
using
readLine
and then use the
StringTokenizer
class to decompose the string
into tokens. Next, use
Integer.parseInt
or a similar method to convert each token
to a number.
Integer.parseInt, Double.parseDouble
, and similar methods that convert
strings to numbers are explained in Chapter 5 in the subsection entitled “Wrapper
Classes.” The
StringTokenizer
class is discussed in Chapter 4 in the starred subsec-
tion entitled “The
StringTokenizer
Class”.
■
Testing for the End of a Text File with
BufferedReader
When using the class
BufferedReader
, if your program tries to read beyond the end
of the file with either of the methods
readLine
or
read
, then the method returns a
special value to signal that the end of the file has been reached. When
readLine
tries
to read beyond the end of a file, it returns the value
null
. Thus, your program can
test for the end of the file by testing to see if
readLine
returns
null
. This technique
is illustrated in Display 10.9 . When the method
read
tries to read beyond the end of
a file, it returns the value
-1
. Because the
int
value corresponding to each ordinary
character is positive, this can be used to test for the end of a file.