// FileCompare.java Copyright (c) 2006 Kari Laitinen // http://www.naturalprogramming.com // 2006-02-21 File created. // 2006-02-21 Last modification. // A solution to Exercise 14-6. import java.util.* ; import java.io.* ; // Classes for file handling. class FileCompare { public static void main( String[] command_line_parameters ) { Scanner keyboard = new Scanner( System.in ) ; String name_of_first_file ; String name_of_second_file ; if ( command_line_parameters.length == 2 ) { name_of_first_file = command_line_parameters[ 0 ] ; name_of_second_file = command_line_parameters[ 1 ] ; } else { System.out.print( "\n This program compares a file" + "\n to another file. Please, give the name of" + "\n the first file: " ) ; name_of_first_file = keyboard.nextLine() ; System.out.print( "\n Give the name of the second file: " ) ; name_of_second_file = keyboard.nextLine() ; } try { FileInputStream first_file = new FileInputStream( name_of_first_file ) ; FileInputStream second_file = new FileInputStream( name_of_second_file ) ; System.out.print( "\n Comparison in progress ... \n" ) ; int number_of_bytes_compared = 0 ; // If this program were used for serious file comparison // operations, it might be better to use a larger array // (input buffer) into which bytes are read. byte[] bytes_from_first_file = new byte[ 128 ] ; byte[] bytes_from_second_file = new byte[ 128 ] ; boolean files_are_equal = true ; boolean comparison_is_ready = false ; while ( files_are_equal == true && comparison_is_ready == false ) { int first_number_of_bytes = first_file.read( bytes_from_first_file ) ; int second_number_of_bytes = second_file.read( bytes_from_second_file ) ; // The following line was used when this program was tested. // System.out.print( " " + first_number_of_bytes + " " // + second_number_of_bytes ) ; // Method read() returns -1 when there is no more data because // the end of file has been encountered. if ( first_number_of_bytes == -1 && second_number_of_bytes == -1 ) { comparison_is_ready = true ; } else if ( first_number_of_bytes != second_number_of_bytes ) { files_are_equal = false ; } else { int byte_index = 0 ; while ( byte_index < first_number_of_bytes && files_are_equal == true ) { if ( bytes_from_first_file[ byte_index ] != bytes_from_second_file[ byte_index ] ) { files_are_equal = false ; } number_of_bytes_compared ++ ; byte_index ++ ; } } } if ( files_are_equal == true ) { System.out.print( "\n The files are equal. " ) ; } else { System.out.print( "\n The files are NOT equal. " ) ; } System.out.print( "\n " + number_of_bytes_compared + " bytes were compared. \n" ) ; first_file.close() ; second_file.close() ; } catch ( FileNotFoundException caught_file_not_found_exception ) { System.out.print( "\n Cannot open both files " ) ; } catch ( IOException caught_io_exception ) { System.out.print( "\n Error while processing the files " ) ; } } }