Java ByteArrayOutputStream-class And Method Code Example


The ByteArrayOutputStream class is part of the Java standard library, not the Apache Commons IO library. However, Apache Commons IO library provides a class IOUtils that has a method toByteArray which can be used to convert an inputstream to byte array.

Here is an example of how to use the ByteArrayOutputStream class from the Java standard library in conjunction with IOUtils class from the Apache Commons IO library in Java to convert an InputStream to a byte array:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

public class InputStreamToByteArrayExample {

    public static void main(String[] args) {
        // Define the InputStream
        InputStream inputStream = getClass().getResourceAsStream("/example.txt");

        try {
            // Convert the InputStream to a byte array
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, outputStream);
            byte[] byteArray = outputStream.toByteArray();
            System.out.println("InputStream converted to byte array.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

This example will convert the InputStream of file 'example.txt' to a byte array and print "InputStream converted to byte array."

IOUtils.closeQuietly method is used here to close the inputstream, it will close the inputstream quietly, meaning it will not throw an exception if the inputstream is already closed.