Java FileInputStream Read readFileBytes(File file)

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

Description

Read the file raw content into byte array.

License

Apache License

Parameter

Parameter Description
fileName a parameter

Declaration

public static final byte[] readFileBytes(File file) throws IOException 

Method Source Code

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

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

import java.io.IOException;

public class Main {
    /**/*from w  ww  .j  av  a  2  s  . c o m*/
     * Read the file raw content into byte array.
     * @param fileName
     * @return
     */
    public static final byte[] readFileBytes(String fileName) throws IOException {
        File file = new File(fileName);
        return readFileBytes(file);
    }

    /**
     * Read the file raw content into byte array.
     * @param fileName
     * @return
     */
    public static final byte[] readFileBytes(File file) throws IOException {
        if (file.exists() && file.isFile()) {
            FileInputStream fis = new FileInputStream(file);
            int fileLen = (int) file.length();
            byte[] buf = new byte[fileLen];
            int len = 0;
            while (len < fileLen) {
                int n = fis.read(buf, len, fileLen - len);
                if (n >= 0) {
                    len += n;
                } else {
                    break;
                }
            }
            return buf;
        } else {
            throw new IOException(file + " does not exist or is not file!");
        }
    }
}

Related

  1. readFileAsResource(String fileName)
  2. ReadFileAsUtf8String(String filePath)
  3. readFileAtOnce(final File file)
  4. readFileBinaries(File file)
  5. readFileBinary(String filename)
  6. readFileBytes(File file)
  7. readFileBytes(String file)
  8. readFileBytes(String filename)
  9. readFileBytes(String fileName)