Reading Binary Data


InputStream is = new FileInputStream(fileName); int offset = 0; int bytesRead =    is.read(bytes, offset, bytes.length-offset);



Using the read() method, we can read binary data from a file into an array of bytes. In this phrase, we read from the is input stream into the bytes byte array. In this phrase, the bytes array is assumed to have been previously initialized as a byte array, and the fileName variable is the name of a valid file. The offset variable points to a starting location in the bytes array to begin writing the data to. This is useful when you are in a loop reading data from a file and you don't want to overwrite previous data stored in the byte array. For each iteration through the loop, you would update the offset location. We've seen this in the previous phrase, Reading a File into a Byte Array. Here is the relevant code example:

while ( (offset < bytes.length)          &&         ( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) ) {        offset += numRead; }


In this code example, we are writing data from the input stream is into the bytes array. We continue to read from the file until we've either filled up the bytes array, or there is no more data to read from the file.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net