Java File to Byte Array getBytesFromFile(final File file)

Here you can find the source of getBytesFromFile(final File file)

Description

Get the bytes of a file.

License

Open Source License

Parameter

Parameter Description
file the file

Exception

Parameter Description
IOException TODO

Return

the bytes of the file

Declaration

public static byte[] getBytesFromFile(final File file) 

Method Source Code


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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /** 4096 *///from w  ww.  j a v  a  2 s. c  o  m
    private static final int BYTE_BUFFER = 4096;

    /**
     * Get the bytes of a file.
     * 
     * @param file
     *            the file
     * @return the bytes of the file
     * @throws IOException
     *             TODO
     */
    public static byte[] getBytesFromFile(final File file) {
        ByteArrayOutputStream ous = null;
        InputStream ios = null;
        try {
            byte[] buffer = new byte[BYTE_BUFFER];
            ous = new ByteArrayOutputStream();
            ios = new FileInputStream(file);
            int read = 0;
            while ((read = ios.read(buffer)) != -1) {
                ous.write(buffer, 0, read);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (ous != null) {
                    ous.close();
                }
                if (ios != null) {
                    ios.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ous.toByteArray();
    }
}

Related

  1. getBytesFromFile(File file)
  2. getBytesFromFile(File file)
  3. getBytesFromFile(File file)
  4. getBytesFromFile(File file)
  5. getBytesFromFile(File inputFile)
  6. getBytesFromFile(String file)
  7. getBytesFromFile(String fileName)
  8. getBytesFromFile(String filename)
  9. getBytesFromFile(String filename)