Java Reference
In-Depth Information
Opening a Text File for Reading with
BufferedReader
You create a stream of the class
BufferedReader
and connect it to a text file for reading as
follows:
SYNTAX
BufferedReader
Stream_Object
=
new
BufferedReader(
new
FileReader(
File_Name
));
EXAMPLE
BufferedReader inputStream =
new
BufferedReader(
new
FileReader("morestuff2.txt"));
After this statement, you can use the methods
readLine
and
read
to read from the file.
When used in this way, the
FileReader
constructor, and hence the
BufferedReader
con-
structor invocation, can throw a
FileNotFoundException
, which is a kind of
IOException
.
Display 10.8
Some Methods of the Class
BufferedReader
(part 1 of 2)
BufferedReader
and
FileReader
are in the
java.io
package.
public
BufferedReader(Reader readerObject)
This is the only constructor you are likely to need. There is no constructor that accepts a file name as
an argument. If you want to create a stream using a file name, you use
new
BufferedReader(
new
FileReader(
File_Name
))
When used in this way, the
FileReader
constructor, and thus the
BufferedReader
constructor
invocation, can throw a
FileNotFoundException
, which is a kind of
IOException
.
The
File
class will be covered in the section entitled “The
File
Class.” We discuss it here so that
you will have a more complete reference in this display, but you can ignore the following reference to
the class
File
until after you've read that section.
If you want to create a stream using an object of the class
File
, you use
new
BufferedReader(
new
FileReader(
File_Object
))
When used in this way, the
FileReader
constructor, and thus the
BufferedReader
constructor
invocation, can throw a
FileNotFoundException
, which is a kind of
IOException
.
public String
readLine()
throws
IOException
Reads a line of input from the input stream and returns that line. If the read goes beyond the end of
the file,
null
is returned. (Note that an
EOFException
is not thrown at the end of a file. The end of a
file is signaled by returning
null
.)