IOExceptions

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:

An IOException is thrown.

IOExceptions

Most IO methods throw an IOException when an error is encountered. A method that uses one of these IO methods must either (1) include throws IOException in its header, or (2) perform its IO in a try{} block and then catch IOExceptions. Here is the example program modified to catch exceptions:

import java.io.*;

class WriteTextFile2
{

  public static void main ( String[] args ) 
  {
    String fileName = "reaper.txt" ;

    try
    {  
      // append characters to the file
      FileWriter writer = new FileWriter( fileName, true );

      writer.write( "Alone she cuts and binds the grain,/n"  );  
      writer.write( "And sings a melancholy strain;/n"  );  
      writer.write( "O listen! for the Vale profound/n" );  
      writer.write( "Is overflowing with the sound./n/n"  );  

      writer.close();
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );
    }
  }
}

The constructor, the write() method, and the close() method can throw an IOException. All are caught by the catch block. The program opens the file reaper.txt for appending. Run it and see what it does.

QUESTION 9:

If you are running a Microsoft operating system, change the permissions of the file reaper.txt to read only. (Right-click on the file name in Explorer and then go to properties). Now run the program again. What happens?