Java File to Byte Array getBytes(File file)

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

Description

Reads a file into a byte array.

License

LGPL

Parameter

Parameter Description
file The file

Exception

Parameter Description
IOException an exception

Return

The byte array

Declaration

public static byte[] getBytes(File file) throws IOException 

Method Source Code

//package com.java2s;
/**//from   w w  w .  j a  v  a2 s  . c  o m
 * Copyright 2009-2012 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */

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

public class Main {
    /**
     * Reads a file into a byte array.
     * 
     * @param file
     *        The file
     * @return The byte array
     * @throws IOException
     */
    public static byte[] getBytes(File file) throws IOException {
        FileInputStream stream = new FileInputStream(file);

        try {
            long length = file.length();

            if (length > Integer.MAX_VALUE)
                throw new IOException("File too big: " + file.getName());

            int ilength = (int) length;
            byte[] bytes = new byte[ilength];
            int alength = stream.read(bytes);

            if (alength != ilength)
                throw new IOException("Only " + alength + " of " + ilength + " bytes read: " + file.getName());

            return bytes;
        } finally {
            stream.close();
        }
    }
}

Related

  1. getBytes(File archiveFile)
  2. getBytes(File contentFile)
  3. getBytes(File f)
  4. getBytes(File f)
  5. getBytes(File f)
  6. getBytes(File file)
  7. getBytes(File file)
  8. getBytes(File file)
  9. getBytes(File file)