java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to read a file into byte array using Commons IO?

The following example shows you how to read file contents into byte array. We use the IOUtils class of the commons-io library.

package com.javacoderanch.example.commons.io;

import org.apache.commons.io.IOUtils;

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

public class FileToByteArray {
    public static void main(String[] args) {
        File file = new File("src/main/resources/Hello.txt");
        try {
            InputStream is = new FileInputStream(file);
            byte[] bytes = IOUtils.toByteArray(is);

            System.out.println("Byte array size: " + bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}