// FilecopyBinaryKL.java Copyright (c) 2006 Kari Laitinen // http://www.naturalprogramming.com // 2006-02-22 File created. // 2006-02-22 Last modification. // This program works in the same way as Filecopy.java except // that the given file is copied as a binary file. // A solution to Exercise 14-7. import java.util.* ; import java.io.* ; // Classes for file handling. class FilecopyBinaryKL { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; 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() ; try { FileInputStream file_to_be_copied = new FileInputStream( name_of_file_to_be_copied ) ; FileOutputStream new_duplicate_file = new FileOutputStream( name_of_new_duplicate_file ) ; System.out.print( "\n Copying in progress ... \n" ) ; int total_number_of_bytes_copied = 0 ; // If this program were used for serious file copying // operations, it might be better to use a larger array // (input buffer) into which bytes are read. byte[] bytes_from_file = new byte[ 128 ] ; int number_of_bytes_read ; while (( number_of_bytes_read = file_to_be_copied.read( bytes_from_file )) > 0 ) { new_duplicate_file.write( bytes_from_file, 0, number_of_bytes_read ) ; total_number_of_bytes_copied += number_of_bytes_read ; } System.out.print( "\n Copying ready. " + total_number_of_bytes_copied + " bytes were copied. \n" ) ; file_to_be_copied.close() ; new_duplicate_file.close() ; } catch ( FileNotFoundException caught_file_not_found_exception ) { System.out.print( "\n Cannot open " + name_of_file_to_be_copied ) ; } catch ( IOException caught_io_exception ) { System.out.print( "\n File error. Probably cannot write to " + name_of_new_duplicate_file ) ; } } }