Read a file into a byte array
by ricardoz on Jul.22, 2008, under Tips
Need to read a file into a byte array in memory, here’s a simple code sample.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | File file = new File("/somepath/myfile.ext"); FileInputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); if (length > Integer.MAX_VALUE) { throw new IOException("The file is too big"); } // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("The file was not completely read: "+file.getName()); } // Close the input stream, all file contents are in the bytes variable is.close(); |
October 22nd, 2008 on 12:54 am
But this code cannot read the doc file which has table in it.. Any help??
October 24th, 2008 on 11:43 am
@stronghead: The code reads any file as binary content, so it really doesn’t mind what’s inside of it. You probably have a problem somewhere else, post your code if you want.
January 26th, 2011 on 8:21 am
Is there a bug here, or did I miss something ?
The bytes buffer address isn’t getting updated during iteratons of the loop.
January 26th, 2011 on 9:45 am
Sorry ignore that – The second param is the offset into the array, not the offset into the file itself.
March 24th, 2011 on 6:32 pm
What about the potential infinite loop if the stream encounters an EOF in the middle of the file and then numRead will continue to be set to 0 and hence will never increase the offset. and then we’ll cycle and cycle.
March 25th, 2011 on 7:12 am
@Jake: from the FileInputStream javadoc
“Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.”
The problem you mention shouldn’t happen since after EOF is found read should always return -1.
May 10th, 2011 on 10:16 am
The loop should be enclosed in a try/finally. ie:
try { readloop } finally { is.close() } otherwise you will leave streams open if there is an error.
Also, for efficiency, you would normally want to wrap your FileInputStream with a BufferedInputStream.
use a