// EditorSimple.java Copyright (c) 2006 Kari Laitinen // http://www.naturalprogramming.com // 2006-02-16 File created. // 2006-02-16 Last modification. // A solution to Exercise 14-4. // This program would be easier to make by using an ArrayList array. // Those arrays are a subject in Chapter 15. import java.util.* ; import java.io.* ; // Classes for file handling. class EditorSimple { static void store_text_lines_to_file( String[] given_array_of_text_lines, int number_of_lines_to_store, String given_file_name ) { try { PrintWriter output_file = new PrintWriter( new FileWriter( given_file_name ) ) ; for ( int line_index = 0 ; line_index < number_of_lines_to_store ; line_index ++ ) { output_file.println( given_array_of_text_lines[ line_index ] ) ; } output_file.close() ; } catch ( IOException caught_io_exception ) { System.out.print( "\n\n Cannot write to file \"" + given_file_name + "\"\n" ) ; } } public static void main( String[] command_line_parameters ) { Scanner keyboard = new Scanner( System.in ) ; String file_name_given_by_user = null ; if ( command_line_parameters.length == 1 ) { file_name_given_by_user = command_line_parameters[ 0 ] ; } System.out.print( "\n This program is a simple text editor. " + "\n Please, start writing text. You can stop by" + "\n writing a dot . into the first column.\n\n" ) ; int number_of_text_lines_given = 0 ; String[] given_text_lines = new String[ 200 ] ; boolean user_wants_to_stop_writing_text = false ; while ( user_wants_to_stop_writing_text == false ) { String text_line_from_user = keyboard.nextLine() ; // We must check the line length in order to allow // lines of zero length to be put into the file. if ( text_line_from_user.length() > 0 && text_line_from_user.charAt( 0 ) == '.' ) { user_wants_to_stop_writing_text = true ; } else { given_text_lines[ number_of_text_lines_given ] = text_line_from_user ; number_of_text_lines_given ++ ; if ( number_of_text_lines_given >= given_text_lines.length ) { System.out.print( "\n\n Sorry, you cannot give more lines! " ) ; user_wants_to_stop_writing_text = true ; } } } if ( file_name_given_by_user == null ) { System.out.print( "\n Please, given the name of the file where" + "\n you want this text to be stored: " ) ; file_name_given_by_user = keyboard.nextLine() ; } System.out.print( "\n Storing text to file " + file_name_given_by_user ) ; store_text_lines_to_file( given_text_lines, number_of_text_lines_given, file_name_given_by_user ) ; } }