Java File to Byte Array fileToBytes(File source)

Here you can find the source of fileToBytes(File source)

Description

Reads the contents of a file as a byte[].

License

Open Source License

Parameter

Parameter Description
source the file

Exception

Parameter Description
IOException an exception

Return

the byte[] with the bytes of the file

Declaration

public static byte[] fileToBytes(File source) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

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

public class Main {
    /**/*www  . jav  a  2s . c  o  m*/
     * Reads the contents of a file as a byte[].  Obviously be careful
     * with memory.
     *
     * @param source the file
     * @return the byte[] with the bytes of the file
     * @throws IOException
     */
    public static byte[] fileToBytes(File source) throws IOException {
        FileInputStream fIn = null;

        try {
            fIn = new FileInputStream(source);
            byte[] bytes = new byte[(int) source.length()];
            int read = 0;
            while (read < bytes.length) {
                int thisRead = fIn.read(bytes, read, bytes.length - read);
                if (thisRead == -1) {
                    throw new IOException("Premature end of stream");
                }
                read += thisRead;
            }
            close(fIn);
            return bytes;
        } catch (IOException ex) {
            close(fIn);
            throw ex;
        }

    }

    /**
     * Safe close of an OutputStream (no exceptions,
     * even if reference is null).
     *
     * @param out the stream to close
     */
    public static void close(OutputStream out) {
        try {
            out.close();
        } catch (Exception ignore) {
        }
    }

    /**
     * Safe close of an InputStream (no exceptions,
     * even if reference is null).
     *
     * @param in the stream to close
     */
    public static void close(InputStream in) {
        try {
            in.close();
        } catch (Exception ignore) {
        }
    }
}

Related

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