Java Reference
In-Depth Information
Self-Test Exercises
(continued)
11. Might the following throw an exception that needs to be caught or declared in
a
throws
clause?
Scanner inputStream =
new
Scanner(
new
FileInputStream("morestuff.txt"));
(The stream
inputStream
would be used to read from the text fi le
morestuff.txt
.
)
Reading a Text File Using
BufferedReader
Until the
Scanner
class was introduced with version 5.0 of Java, the class
BufferedReader
was the preferred stream class to use for reading from a text file. It
is still a commonly used class for reading from a text file. The use of
BufferedReader
is illustrated in Display 10.7, which contains a program that reads two lines from
a text file named
morestuff2.txt
and writes them back to the screen. The file
morestuff2.txt
is a text file that a person could have created with a text editor or that
a Java program could have created using
PrintWriter
.
The program opens the text file
morestuff2.txt
as follows:
Buffered
Reader
opening a file
BufferedReader inputStream =
new
BufferedReader(
new
FileReader("morestuff2.txt"));
The class
BufferedReader
, like the classes
PrintWriter
and
Scanner
, has no
constructor that takes a file name as its argument, so we need to use another class—in
this case, the class
FileReader
—to convert the file name to an object that can be an
argument to
BufferedReader
.
An object of the class
BufferedReader
that is connected to a text file, as in Display 10.7,
has a method named
readLine
that is like the method
nextLine
of the
Scanner
class.
This use of
readLine
to read from a text file is illustrated in Display 10.7.
Display 10.8 describes some of the methods in the class
BufferedReader
. Notice
that there are only two methods for reading from a text file,
readLine
and
read
. We
have already discussed
readLine
.
readLine
Display 10.7
Reading Input from a Text File Using
BufferedReader
(part 1 of 2)
1
import
java.io.BufferedReader;
2
import
java.io.FileReader;
3
import
java.io.FileNotFoundException;
4
import
java.io.IOException;
5
public class
TextFileInputDemo
6 {
7
public static void
main(String[] args)
8 {
(continued)