go to previous page   go to home page   go to next page

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 worth while 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?