Reading Data from a File

This chapter discusses Java's FileReader and BufferedReader classes in detail. FileReader and BufferedReader classes are used together when reading data from an external file. The use of the BufferedReader class allows data to be buffered as it is read from a file before manipulating it. The readLine() method of the BufferedReader class reads a line of text from a character-oriented input stream, and puts it into a new String object.

4. Example Program


Answer:

The readLine() method.

Example Program


import java.io.*;
class ReadTextFile
{
 public static void main ( String[] args ) 
 {
   String fileName = "reaper.txt" ;
   String line;

   try
   {      
     BufferedReader in = new BufferedReader( new FileReader( fileName  ) );
     
     line = in.readLine();
     while ( line != null )  // while not end of file
     {
       System.out.println( line );
       line = in.readLine();
     }
     in.close();
   }
   catch ( IOException iox )
   {
     System.out.println("Problem reading " + fileName );
   }
 }
}

The readLine() method reads a line of text from a character-oriented input stream, and puts it into a new String object which it returns as a reference. If there is no more data in the file, it returns null.

When a file is opened it is prepared for use. This program opens a file for reading. (The analogy is to opening a paper file in an office.)

The file reaper.txt is opened for reading when the FileReader stream is constructed. If the file does not exist in the current directory, an IOException is thrown.

Next, the program reads each line of the file and writes it to the monitor. When end-of-file is detected the program quits.

This is an extremely common programming pattern: reading and processing data while not end-of-file. Usually in documentation, end-of-file is abbreviated EOF.

It would be worthwhile to play with this program. Create reaper.txt with a text editor if it does not already exist.

Question 4:

Does this program create a new String object for each line of text in the file?