Java FileInputStream Read readFile(String fileName)

Here you can find the source of readFile(String fileName)

Description

Reads a file and return its content as a byte array.

License

Open Source License

Parameter

Parameter Description
fileName the file to load.

Exception

Parameter Description
IOException an exception

Return

the byte array of its content.

Declaration

public static byte[] readFile(String fileName) throws IOException 

Method Source Code


//package com.java2s;

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

import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**/*  www.j  a  v  a 2 s.c  o m*/
     * Reads a file and return its content as a byte array.
     * @param file the file to load.
     * @return the byte array of its content.
     * 
     */
    public static byte[] readFile(File file) {
        byte[] bytes = null;

        ByteArrayOutputStream buffer = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            buffer = new ByteArrayOutputStream();

            byte[] dataRead = new byte[16384];
            int nbBytesRead;

            while ((nbBytesRead = inputStream.read(dataRead)) != -1) {
                buffer.write(dataRead, 0, nbBytesRead);
            }

            buffer.flush();
            bytes = buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (buffer != null) {
                try {
                    buffer.close();
                } catch (IOException e) {
                    ;
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    ;
                }
            }
        }

        return bytes;
    }

    /**
     * Reads a file and return its content as a byte array.
     * @param fileName the file to load.
     * @return the byte array of its content.
     * @throws IOException
     */
    public static byte[] readFile(String fileName) throws IOException {
        return readFile(new File(fileName));
    }
}

Related

  1. readFile(String fileName)
  2. readFile(String filename)
  3. readFile(String fileName)
  4. readFile(String filename)
  5. readFile(String fileName)
  6. readFile(String filename)
  7. readFile(String filename)
  8. readFile(String fileName)
  9. readFile(String filename)