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.