The following example, TextFileReadApp,
illustrates how to use the FileReader
stream to read strings from a text file. The goal is to read a
file and count the number of lines in which a particular string
occurs at least once.
We wrap the FileReader
stream with a BufferedReader
class and take advantage of its readLine()
method to read a whole line at a time. We use the indexOf()
method in the String
class to search for the string of interest.
As usual, we enclose the stream reading within a
try-catch
statement to catch the IOException
or one of its subclass exceptions that can be thrown by the stream
constructors and the read methods.
|
import
java.io.*;
import java.util.*;
/** Demonstrate reading text from a file.**/
public class TextFileReadApp
{
public static void main (String arg[]) {
// Count the number of lines in
which the string occurs
String string_to_find = "new";
File file = null;
// Get the file from the argument
line.
if (arg.length > 0) file = new File
(arg[0]);
if (file == null || !file.exists
()) {
System.out.println ("Default:
TextFileReadApp.java");
file = new File ("TextFileReadApp.java");
}
// Count the number of lines with
the string of interest.
int num_lines = 0;
try {
// Create a FileReader
and then wrap it with BufferedReader.
FileReader file_reader
= new FileReader (file);
BufferedReader buf_reader
= new BufferedReader (file_reader);
// Read each line of
the file and look for the string of interest.
do {
String
line = buf_reader.readLine ();
if (line
== null) break;
if (line.indexOf(string_to_find)
!= -1) num_lines++;
} while (true);
buf_reader.close ();
}
catch (IOException e) {
System.out.println
("IO exception =" + e );
}
System.out.printf ("Number of lines
containing \"%s\" = %3d %n",
string_to_find, num_lines);
} // main
} //class TextFileReadApp
|
If we let the program examine the default input
file, then the output will go as
Note that we close the stream explicitly. For this
short program, which stops soon after finishing the read, closing
the input stream is not a big deal, but in general, it is good
practice to always close input and output streams when I/O transfers
are completed.
References &
Web Resources
Latest update: Dec. 9, 2004