// TextLinesToFile.java Copyright (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2005-06-27 File created. // 2005-06-27 Last modification. /*** This program was used to test the try-catch-finally construct in file writing operations. In the following example run, the file is temporarily made a read-only file before the program is executed. It is not possible to write to a read-only file, and thus the program throws an exception. D:\javafilesextra>attrib +R TextLinesToFile_output.txt D:\javafilesextra>java TextLinesToFile TextLinesToFile_output.txt exists File error. Cannot write to file. Exception info: java.io.FileNotFoundException: TextLinesToFile_output.txt (Acce ss is denied) D:\javafilesextra>attrib -R TextLinesToFile_output.txt ****/ import java.util.* ; import java.io.* ; // Classes for file handling. class TextLinesToFile { public static void main( String[] not_in_use ) { String name_of_file_as_string = "TextLinesToFile_output.txt" ; File file_to_use = new File( name_of_file_as_string ) ; if ( file_to_use.exists() ) { System.out.print( "\n " + name_of_file_as_string + " exists " ) ; } else { System.out.print( "\n " + name_of_file_as_string + " does NOT yet exist " ) ; } PrintWriter file_to_write = null ; try { file_to_write = new PrintWriter( new FileWriter( "TextLinesToFile_output.txt" ) ) ; for ( int line_number = 1 ; line_number < 4 ; line_number ++ ) { file_to_write.println( "This is line " + line_number ) ; } } catch ( IOException caught_io_exception ) { System.out.print( "\n File error. Cannot write to file. " ) ; System.out.print( "\n Exception info: " + caught_io_exception ) ; } finally { if ( file_to_write != null ) { file_to_write.close() ; } } } }