// FileToNumbers.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2003-12-10 File created. // 2005-11-19 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. // In the javafilesextra folder you can find a program // named FileToNumbersAlternative.java which works like this // program but it asks the file name from the user. import java.io.* ; class FileToNumbers { public static void main( String[] command_line_parameters ) { 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 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 ) ; } 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 FileToNumbers file.ext \n") ; } } } /* NOTES: This program uses Java 2 Standard Edition, Version 1.5 features. Compilation with older Java compilers is thus not possible. */