This preview shows page 1. Sign up to view the full content.
Unformatted text preview: e possible
way to call the read() method is the following:
byte bytes_from_file = new byte[ 50 ] ; int number_of_bytes_read =
file_to_read.read( bytes_from_file ) ; This method call could be "translated" as follows: "Here is this array of bytes. Please, read
bytes from the file and put them to the array, starting from the array position that has index
0. Read 50 bytes at maximum because that is the length of the array; it cannot hold any
more bytes." After receiving these orders, the read() method would do its job and return
the number of bytes it was able to read. The read() method checks the length of the given
array of type byte, and automatically delivers as many bytes as is the length of the
Files are typically read with a loop, but the loop that uses method read() becomes
somewhat complicated as the above method call must be fitted into it. One possibility to
construct a loop that calls method read() is the following one which calculates the size of
a file by counting how many bytes the file contains: 470 Chapter 14: Storing information in files byte bytes_from_file = new int file_size_in_bytes = 0; int number_of_bytes_read = byte[ 50 ] ; 0; while (( number_of_bytes_read =
file_to_read.read( bytes_from_file ))
file_size_in_bytes = file_size_in_bytes +
// > 0) This loop does not do anything to the read data. } In the above case, method read() is called in the somewhat complicated boolean
expression of the while loop. When the boolean expression is evaluated, the read()
method is called, and as a result variable number_of_bytes_read gets a new value, and
that value is then compared to zero. The boolean expression is true as long as the read()
method is able to read bytes from the file.
Method read() works with binary files in the same manner as method readLine()
works with text files. In the loop above, when method read() is called for the first time,
it reads the first 50 bytes from the file, and subsequent calls read the file from the position
where the previous reading operation stopped. The above lo...
View Full Document
This document was uploaded on 01/20/2014.
- Winter '14