Java Utililty Methods File to Byte Array

List of utility methods to do File to Byte Array

Description

The list of methods to do File to Byte Array are organized into topic(s).

Method

byte[]getBytesFromFile(final File file)
Get the bytes of a 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) {
...
byte[]getBytesFromFile(String file)
get Bytes From File
byte[] res = null;
try {
    File f = new File(file);
    FileInputStream fin = new FileInputStream(f);
    res = new byte[fin.available()];
    int b = fin.read(res);
    if (b != res.length) {
        return null;
...
byte[]getBytesFromFile(String filename)
get Bytes From File
File f = new File(filename);
if (!f.exists()) {
    throw new FileNotFoundException(filename);
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
    in = new BufferedInputStream(new FileInputStream(f));
...
byte[]getBytesFromFile(String filename)
returns byte array containing contents of file at specified path
File f = new File(filename);
long len = f.length();
if (len >= (1L << 32))
    throw new RuntimeException("File " + filename + " is larger than 2^32 bytes: " + len);
BufferedInputStream is = new BufferedInputStream(new FileInputStream(f));
int int_len = (int) len;
byte b[] = new byte[int_len];
int totalBytesRead = 0;
...
byte[]getBytesFromFile(String fileName)
get Bytes From File
byte[] result = null;
try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
    byte[] buff = new byte[2048];
    FileInputStream fis = new FileInputStream(fileName);
    while (true) {
        int len = fis.read(buff);
        if (len == -1) {
...
byte[]getBytesFromFile(String filename)
Given name of file, return entire file as a byte array.
File f = new File(filename);
byte[] bytes = null;
if (f.exists()) {
    try {
        bytes = getBytesFromFile(f);
    } catch (Exception e) {
        System.out.println("getBytesFromFile() exception: " + e);
return bytes;
byte[]getBytesFromFile(String filepath)
get Bytes From File
File file = new File(filepath);
InputStream is = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
    offset += numRead;
...
byte[]getBytesFromFile(String filePath)
get Bytes From File
return getBytesFromFile(new File(filePath));
byte[]toByteArray(File file)
to Byte Array
FileInputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
    inputStream = new FileInputStream(file);
    int read = 0;
    byte[] buffer = new byte[4096];
    while ((read = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, read);
...