Java File to Byte Array getBytes(File aFile)

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

Description

Returns bytes for a file.

License

Open Source License

Declaration

public static byte[] getBytes(File aFile) 

Method Source Code


//package com.java2s;
import java.io.*;

public class Main {
    /**//w w  w. ja v  a  2s.  c  om
     * Returns bytes for a file.
     */
    public static byte[] getBytes(File aFile) {
        // Return null if file is null, doesn't exist, isn't readable or is directory
        if (aFile == null)
            return null;
        if (!aFile.exists())
            return null;
        if (!aFile.canRead())
            return null;
        if (aFile.isDirectory())
            return null;

        // Get file length, byte buffer, file stream, read bytes into buffer and close stream
        try {
            int length = (int) aFile.length();
            byte bytes[] = new byte[length];
            InputStream stream = new FileInputStream(aFile);
            stream.read(bytes, 0, length);
            stream.close();
            return bytes;
        }

        // Re-throw exceptions
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

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