Reading a File into a Byte Array


File file = new File(fileName); InputStream is = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while ((offset < bytes.length)          &&         ((numRead=is.read(bytes,                            offset,                            bytes.length-offset))          >= 0)) {        offset += numRead; } is.close();



This phrase will read the file specified by fileName into the bytes byte array. Notice that the file.length() method returns us the length of the file in bytes as a long value, but we must use an int value to initialize the byte array, so we cast the long value to an int value. In a real program, you would probably want to be sure that the length value would indeed fit into an int type before blindly casting it. Using the read() method of the InputStream, we continue to read in bytes from the file until either the byte array is filled up, or there are no more bytes 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