// Examine.java Copyright (c) 2006 Kari Laitinen // http://www.naturalprogramming.com // 2006-02-22 File created. // 2006-02-22 Last modification. // The best way to execute this program is to run it in a // command prompt window where command line parameters can // be given. It may be difficult, and even impossible, to // supply the command line parameters if this program is // executed with a modern development tool such as JCreator // or Eclipse. // A solution to Exercise 14-8. import java.util.Scanner ; import java.io.* ; // Classes for file handling. class Examine { public static void main( String[] command_line_parameters ) { Scanner keyboard = new Scanner( System.in ) ; if ( command_line_parameters.length == 1 ) { try { FileInputStream file_to_read = new FileInputStream( command_line_parameters[ 0 ] ) ; byte[] bytes_from_file = new byte[ 16 ] ; int lines_printed_since_last_pause = 0 ; int number_of_bytes_read ; while (( number_of_bytes_read = file_to_read.read( bytes_from_file )) > 0 ) { StringBuilder line_of_bytes = new StringBuilder() ; StringBuilder bytes_as_characters = new StringBuilder () ; for ( int byte_index = 0 ; byte_index < number_of_bytes_read ; byte_index ++ ) { line_of_bytes.append( String.format( " %02X", bytes_from_file[ byte_index ] ) ) ; char byte_as_character = (char) bytes_from_file[ byte_index ] ; if ( byte_as_character >= ' ' ) { bytes_as_characters.append( byte_as_character ) ; } else { bytes_as_characters.append( ' ' ) ; } } System.out.printf( "\n%-48s %s", line_of_bytes, bytes_as_characters ) ; lines_printed_since_last_pause ++ ; if ( lines_printed_since_last_pause > 22 ) { System.out.print( "\n Press the Enter key to continue ..." ) ; String any_string_from_keyboard = keyboard.nextLine() ; lines_printed_since_last_pause = 0 ; } } file_to_read.close() ; } catch ( FileNotFoundException caught_file_not_found_exception ) { System.out.print( "\n Cannot open file " + command_line_parameters[ 0 ] ) ; } catch ( IOException caught_io_exception ) { System.out.print( "\n Error while processing file " + command_line_parameters[ 0 ] ) ; } } else { System.out.print( "\n You have to command this program as: \n" + "\n java Examine file.ext \n") ; } } }