s t r i n g etc classes fileoutputstream and

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: c. Classes FileOutputStream and FileInputStream provide methods write() and read() for writing or reading a certain number of bytes to/from a file. int DataInputStream short object File on disk FileInputStream object char ... S t r i n g Array of bytes Class DataInputStream provides methods like readInt(), readShort(), readChar(), and readUTF() to read various kinds of data items from a binary file. Here, the DataInputStream object communicates with the FileInputStream object to get data from the disk. Figure 14-3. Co-operation of classes in binary file access. etc. 474 // Chapter 14: Storing information in files FileToNumbers.java import java.io.* ; The file is treated as a binary file. Method read() reads 16 bytes from the file at a time because the length of the array bytes_from_file is 16. The first call to method read() reads the first 16 bytes, the second call reads the following 16 bytes, and so on. This while loop is executed as long as there are bytes available in the file. 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 int number_of_bytes_read = new byte[ 16 ] ; ; 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 { The non-printable bytes_as_characters.append( ' ' ) ; characters are shown } as spaces. } System.out.printf( "\n%-48s %s", line_of_bytes, bytes_as_characters ) ; } It is possible to print characters stored in StringBuilder objects with the printf() method. The format specifier %-48s st...
View Full Document

This document was uploaded on 01/20/2014.

Ask a homework question - tutors are online