Java File to Byte Array getBytesFromFile(File file)

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

Description

Returns the contents of the file in a byte array.

License

Apache License

Declaration

public static byte[] getBytesFromFile(File file) throws FileNotFoundException, IOException 

Method Source Code

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**//from  w  w w . ja va 2  s.  c om
     * Returns the contents of the file in a byte array.
     */
    public static byte[] getBytesFromFile(File file) throws FileNotFoundException, IOException {
        byte[] result = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            long fileLength = file.length();
            if (fileLength > Integer.MAX_VALUE) {
                throw new IOException("File too large: " + file.getAbsolutePath());
            }
            result = new byte[(int) fileLength];

            int offset = 0;
            int numRead = 0;
            while ((offset < result.length) && (numRead = in.read(result, offset, result.length - offset)) >= 0) {
                offset += numRead;
            }

            if (offset < result.length) {
                throw new IOException("Could not completely read file:" + file.getAbsolutePath());
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return result;
    }
}

Related

  1. getBytesFromFile(File file)
  2. getBytesFromFile(File file)
  3. getBytesFromFile(File file)
  4. getBytesFromFile(File file)
  5. getBytesFromFile(File file)
  6. getBytesFromFile(File file)
  7. getBytesFromFile(File file)
  8. getBytesFromFile(File file)
  9. getBytesFromFile(File inputFile)