Java FileInputStream Read readFileToByteArray(File file)

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

Description

read File To Byte Array

License

Apache License

Declaration

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

Method Source Code


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

import java.io.*;

public class Main {
    private static final int EOF = -1;

    public static byte[] readFileToByteArray(File file) throws IOException {
        InputStream in = null;/*from  w w  w.j  av a 2s  .co m*/
        try {
            in = openInputStream(file);
            return toByteArray(in, file.length());
        } finally {
            closeQuietly(in);
        }
    }

    public static FileInputStream openInputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canRead() == false) {
                throw new IOException("File '" + file + "' cannot be read");
            }
        } else {
            throw new FileNotFoundException("File '" + file + "' does not exist");
        }
        return new FileInputStream(file);
    }

    public static byte[] toByteArray(InputStream input, long size) throws IOException {
        if (size > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size);
        }
        return toByteArray(input, (int) size);
    }

    public static byte[] toByteArray(InputStream input, int size) throws IOException {
        if (size < 0) {
            throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
        }
        if (size == 0) {
            return new byte[0];
        }
        byte[] data = new byte[size];
        int offset = 0;
        int readed;
        while (offset < size && (readed = input.read(data, offset, size - offset)) != EOF) {
            offset += readed;
        }
        if (offset != size) {
            throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size);
        }
        return data;
    }

    public static void closeQuietly(InputStream is) {
        try {
            ((Closeable) is).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related

  1. readFileInByteArray(String aFileName)
  2. readFileRaw(File file)
  3. readFileToBinary(File lessCSS)
  4. readFileToByteArray(File file)
  5. readFileToByteArray(File file)
  6. readFileToByteArray(String file)
  7. readFileToByteArray(String filename)
  8. readFileToBytes(File f)
  9. readFileToBytes(File f, int max)