// FilecopyCommand.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-2. import java.util.* ; import java.io.* ; // Classes for file handling. class FilecopyCommand { static void copy_file( String name_of_file_to_be_copied, String name_of_new_duplicate_file ) { try { BufferedReader file_to_be_copied = new BufferedReader( new FileReader( name_of_file_to_be_copied ) ) ; PrintWriter new_duplicate_file = new PrintWriter( new FileWriter( name_of_new_duplicate_file ) ) ; System.out.print( "\n Copying in progress ... \n" ) ; int text_line_counter = 0 ; boolean end_of_input_file_encountered = false ; while ( end_of_input_file_encountered == false ) { String text_line_from_file = file_to_be_copied.readLine() ; if ( text_line_from_file == null ) { end_of_input_file_encountered = true ; } else { new_duplicate_file.println( text_line_from_file ) ; text_line_counter ++ ; } } System.out.print( "\n Copying ready. " + text_line_counter + " lines were copied. \n" ) ; file_to_be_copied.close() ; new_duplicate_file.close() ; } catch ( FileNotFoundException caught_file_not_found_exception ) { System.out.print( "\n\n File \"" + name_of_file_to_be_copied + "\" not found.\n" ) ; } catch ( IOException caught_io_exception ) { System.out.print( "\n\n File error. Probably cannot write to \"" + name_of_file_to_be_copied + "\".\n" ) ; } } public static void main( String[] command_line_parameters ) { Scanner keyboard = new Scanner( System.in ) ; if ( command_line_parameters.length == 2 ) { copy_file ( command_line_parameters[ 0 ], command_line_parameters[ 1 ] ) ; } else { System.out.print( "\n This program copies text from one file" + "\n to another file. Please, give the name of" + "\n the file to be copied: " ) ; String name_of_file_to_be_copied = keyboard.nextLine() ; System.out.print( "\n Give the name of the duplicate file: " ) ; String name_of_new_duplicate_file = keyboard.nextLine() ; copy_file( name_of_file_to_be_copied, name_of_new_duplicate_file ) ; } } }