Java File to Byte Array getBytesFromFile(File inputFile)

Here you can find the source of getBytesFromFile(File inputFile)

Description

This method reads a file and convert it into bytes

License

LGPL

Parameter

Parameter Description
inputFile File to be read

Exception

Parameter Description
FileNotFoundException If file is not found
IOException Any error occurred during the operation

Return

bytes read from the file

Declaration

public static byte[] getBytesFromFile(File inputFile)
        throws IOException 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**//from ww w  .  ja  v  a 2s .  c o  m
     * <p>
     * This method reads a file and convert it into bytes
     * </p>
     * 
     * @param inputFile
     *            File to be read
     * @return bytes read from the file
     * @throws FileNotFoundException
     *             If file is not found
     * @throws IOException
     *             Any error occurred during the operation
     */
    public static byte[] getBytesFromFile(File inputFile)
            throws IOException {
        InputStream inputStream = new FileInputStream(inputFile);
        long length = inputFile.length();

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

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        if (offset < outputBytes.length) {
            numRead = inputStream.read(outputBytes, offset,
                    outputBytes.length - offset);
            while (offset < outputBytes.length && numRead >= 0) {
                offset += numRead;
                numRead = inputStream.read(outputBytes, offset,
                        outputBytes.length - offset);
            }
        }

        // Ensure all the bytes have been read in
        if (offset < outputBytes.length) {
            throw new IOException("Could not completely read file "
                    + inputFile.getName());
        }

        // Close the input stream and return bytes
        inputStream.close();
        return outputBytes;
    }
}

Related

  1. getBytesFromFile(File file)
  2. getBytesFromFile(File file)
  3. getBytesFromFile(File file)
  4. getBytesFromFile(File file)
  5. getBytesFromFile(File file)
  6. getBytesFromFile(final File file)
  7. getBytesFromFile(String file)
  8. getBytesFromFile(String fileName)
  9. getBytesFromFile(String filename)