An IOException
is thrown.
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 ); } } }
Most I/O methods throw
an IOException
when an error is encountered.
A method that uses one of these I/O methods
must either (1) include throws IOException
in its header, or (2) perform its I/O in a
try{}
block and then catch
IOExceptions.
The above program is modified to catch exceptions.
The constructor, the write()
method, and the close()
method each
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.
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?