Java Reference
In-Depth Information
Display 10.8
Some Methods of the Class
BufferedReader
(part 2 of 2)
public int
read()
throws
IOException
Reads a single character from the input stream and returns that character as an
int
value. If the
read goes beyond the end of the file, then
-1
is returned. Note that the value is returned as an
int
.
To obtain a
char
, you must perform a type cast on the value returned. The end of a file is signaled
by returning
-1
. (All of the “real” characters return a positive integer.)
public long
skip(
long
n)
throws
IOException
Skips
n
characters.
public void
close()
throws
IOException
Closes the stream's connection to a file.
read
method
The method
read
reads a single character. But note that
read
returns a value of
type
int
that corresponds to the character read; it does not return the character itself.
Thus, to get the character, you must use a type cast, as in
char
next = (
char
)(inputStream.read());
If
inputStream
is in the class
BufferedReader
and is connected to a text file, this will
set
next
equal to the first character in the file that has not yet been read.
Notice that the program in Display 10.7 catches two kinds of exceptions,
FileNotFoundException
and
IOException
. An attempt to open the file may throw
a
FileNotFoundException
, and any of the invocations of
inputStream.readLine()
may throw an
IOException
. Because
FileNotFoundException
is a kind of
IOException
, you could use only the
catch
block for
IOException
. However, if you
were to do this, then you would get less information if an exception were thrown. If you
use only one
catch
block and an exception is thrown, you will not know if the problem
occurred when opening the file or when reading from the file after it was opened.
Self-Test Exercises
12. Write some code that will create a stream named
fileIn
that is a member of
the class
BufferedReader
and that connects the stream to a text fi le named
joe
so that your program can read input from the text fi le
joe
.
13. What is the type of a value returned by the method
readLine
in the class
BufferedReader
? What is the type of a value returned by the method
read
in
the class
BufferedReader
?
14. Might the methods
read
and
readLine
in the class
BufferedReader
throw an
exception? If so, what type of exception?