The above loop reads 50 byte data blocks from the

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: op reads 50-byte data blocks from the file until it has read the last block. Only the last block is likely to be less than 50 bytes in length. In file reading operations it is usually not known when the final data at the end of a file is going to be read. Therefore, a loop that reads a file must always be prepared to encounter the end of file. The above loop can be made easier to understand if a boolean variable is used in the following way: byte = new file_size_in_bytes int bytes_from_file = 0; boolean byte[ 50 ] ; bytes_still_available_in_file = true ; while ( bytes_still_available_in_file == true ) { int number_of_bytes_read = file_to_read.read( bytes_from_file ) ; if ( number_of_bytes_read > 0 ) { file_size_in_bytes = file_size_in_bytes + number_of_bytes_read ; // This loop does not do anything to the read data. } else { bytes_still_available_in_file = false ; } } This loop is, however, somewhat longer than the first loop. For this reason I ended up using a loop like the first one in program FileToNumbers.java. Program FileToNumbers.java demonstrates how a file is read as a binary file. It also shows that a text file can be treated as a binary file. The program reads a file in 16byte blocks and displays the bytes as hexadecimal numbers on the screen. Those bytes that represent character codes of visible characters are also shown as characters. 14.3 Handling files as binary files 471 When you want to write data to a binary file, you can use class FileOutputStream to create an object that represents a binary file for writing operations. One possible file opening statement is the following FileOutputStream binary_file_for_writing = new FileOutputStream( file_name_as_string) ; Here, the constructor of class FileOutputStream opens the file whose name it gets as a parameter. The file is opened so that it is created if it does not exist, and if it exists, it is overwritten with new data. Just as class FileInputStream provides methods named read() to read bytes from binary files, the FileOutputStream class provides methods named write() for writing bytes to binary files. Supposing that a file is opene...
View Full Document

This document was uploaded on 01/20/2014.

Ask a homework question - tutors are online