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

Answer:

No. It cannot be the final destination of data, so it should be connected to some other stream.


Updated Example

import java.io.*;
class WriteTextFile3
{
  public static void main ( String[] args ) 
  {
    String fileName = "reaper.txt" ;
    PrintWriter print = null;

    try
    {       
      print = new PrintWriter( new BufferedWriter( new FileWriter( fileName  ) ) );
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );
    }

    print.println( "No Nightingale did ever chaunt"  );  
    print.println( "More welcome notes to weary bands"  );  
    print.println( "Of travellers in some shady haunt," );  
    print.println( "Among Arabian sands."  );  

    print.close();
  }
}

The updated example program uses a BufferedWriter and a PrintWriter. The println() prints one line of text and ends each line with the correct codes for whatever operating system you are running.

Creating the file might throw an exception, so a try/catch structure is needed for the constructor. However the println() statements do not throw exceptions and can be moved outside of the structure.


QUESTION 15:

Is close() necessary in this program?