Updated Example

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
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

The updated example program uses a BufferedWriter and a PrintWriter. Look at the file it creates with a text editor. The lines of text will be correctly separated for the operating system you are running.

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();
  }
}

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

QUESTION 15:

Is close() necessary in this program?