Java File to Byte Array getBytesFromFile(String filename)

Here you can find the source of getBytesFromFile(String filename)

Description

get Bytes From File

License

Apache License

Declaration

public static byte[] getBytesFromFile(String filename) throws IOException 

Method Source Code


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

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

public class Main {
    public static byte[] getBytesFromFile(String filename) throws IOException {
        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }//from w ww.j  a  v a2s .  co m

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }
}

Related

  1. getBytesFromFile(final File file)
  2. getBytesFromFile(String file)
  3. getBytesFromFile(String filename)
  4. getBytesFromFile(String fileName)
  5. getBytesFromFile(String filename)
  6. getBytesFromFile(String filepath)
  7. getBytesFromFile(String filePath)
  8. toByteArray(File file)