Java FileInputStream Read readFileToBytes(String path)

Here you can find the source of readFileToBytes(String path)

Description

Read file contents into byte array, which is suitable for small files.

License

Apache License

Parameter

Parameter Description
String File path

Return

byte[] File contents

Declaration

public static byte[] readFileToBytes(String path) throws IOException, FileNotFoundException 

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;

public class Main {
    /**//from   w  w  w  . j a  v  a  2 s  .c  om
     * Read file contents into byte array, which is suitable for small files.
     * 
     * @param   String    File path
     * @return   byte[]    File contents
     */
    public static byte[] readFileToBytes(String path) throws IOException, FileNotFoundException {
        File file = new File(path);
        FileInputStream fin = new FileInputStream(path);

        // First, we need to test if the file size is too large for maximum byte array length
        if (file.length() >= Integer.MAX_VALUE) {
            System.out.println("File size is too big. Please use another function to read the contents!");
            return null;
        }

        byte[] contents = new byte[(int) (file.length())];

        fin.read(contents);

        fin.close();

        return contents;
    }
}

Related

  1. readFileToByteArray(File file)
  2. readFileToByteArray(String file)
  3. readFileToByteArray(String filename)
  4. readFileToBytes(File f)
  5. readFileToBytes(File f, int max)
  6. readFileToStr(String fn, String charset)
  7. readFileUTF8(String file)
  8. readFileUTF_8(String filePath)
  9. writeFile(File file, byte[] buffer, ZipOutputStream zos)