Java Reference
In-Depth Information
12.9.5 Text input
The complement to the output of text with a FileWriter is the input with a FileReader . As you
might expect, a complementary set of three input steps is required: opening the file, reading from
it, and closing it. Just as the natural units for writing text are characters and strings, the obvious
units for reading text are characters and lines. However, although the FileReader class contains
a method to read a single character, 6 it does not contain a method to read a line. The problem with
reading lines from a file is that there is no predefined limit to the length of a line. This means that
any method to return the next complete line from a file must be able to read an arbitrary number of
characters. For this reason, we usually want to be working with the BufferedReader class, which
does define a readLine method. However, BufferedReader cannot open files! Therefore,
we must create a FileReader first and immediately wrap it in a BufferedReader object.
Thereafter, we ignore the FileReader object and work solely with the BufferedReader .
The line-termination character is always removed from the String that readLine returns, and
a null value is used to indicate the end of file.
This suggests the following basic pattern for reading the contents of a text file:
try {
BufferedReader reader = new BufferedReader(
new FileReader(" ... name of file ... "));
String line = reader.readLine();
while(line != null) {
do something with line
line = reader.readLine();
catch(FileNotFoundException e) {
the specified file could not be found
catch(IOException e) {
something went wrong with reading or closing
Note that we don't even bother to store the FileReader object into a variable, but pass it
straight to the constructor of BufferedReader . This avoids the confusion of having two
Reader variables referring to the same source of input, because we should access the file only
via the BufferedReader object.
With Java 7, we would use a try-with-resources statement here, as above, but also see below for
an alternative way to create the BufferedReader via the Files class.
Code 12.21 illustrates the practical use of a BufferedReader in the tech-support project from
Chapter 5. This has been done so that we can read the system's default responses from a file
rather than hardwiring them into the code of the Responder class (project: tech-support-io ).
In fact, its read method returns each character as an int value rather than as a char , because it uses
an out-of-bounds value, -1, to indicate the end of the file. This is exactly the sort of technique we de-
scribed in Section 12.3.2.
Search WWH ::

Custom Search