Monday, May 04, 2009

How to Convert a File to a Byte Array

I wrote an EJB which performs faxing using gnu-hylafax for Java. The trick is that I needed to convert the file to bytes[] to pass to the EJB. Here is how I did it, but it should work for most files.

* Converts a file into a byte[] array.
* @param file file to be converted
* @return file converted to {@code byte[]}
* @throws
public static byte[] getBytesFromFile(final File file) throws IOException {
InputStream is = new FileInputStream(file);

// Get the size of the file
long length = file.length();

if (length > Integer.MAX_VALUE) {
/* File is too large. If we are trying to determine the length of the byte[]
* array, it can only return an int, so we are limited by the file size.
throw new IOException(file.getName() + " is too large.");

// Create the byte array to hold the data
byte[] data = new byte[(int) length];

// Read in the bytes
int offset = 0;
int bytesRead = 0;
while (offset < data.length &&
(bytesRead =, offset, data.length - offset)) >= 0) {
offset += bytesRead;

// Ensure all the bytes have been read in
if (offset < data.length) {
throw new IOException("An exception occurred while trying to read + "
+ file.getName() + " into the byte array.");

// Close the input stream and return bytes
return data;


Popular Posts