How to Write InputStream to OutputStream in Java

This article illustrates a different ways of Writing an InputStream to an OutputStream by using Apache Commons IO, Guava, and Core Java.

Overview

In this tutorial, we will cover various examples of writing InputStream to OutputStream. First we will begin with Core Java iterative approach, and then have a look at a utility method, which provides a convenient abstraction. After that, we will see how popular libraries like Apache Commons IO and Guava support Converting InputStream to OutputStream.

Using Java Iterative Buffers Copy

Using vanilla Java, we can create buffer and fill it iteratively to copy the bytes.

Next is an example of Core Java – InputStream to OutputStream conversion.

byte[] bucket = new byte[1024];
int bytesRead;
try (OutputStream outputStream = new FileOutputStream(outputPath)) {
    while ((bytesRead = inputStream.read(bucket)) != -1) {
        outputStream.write(bucket, 0, bytesRead);
    }
}Code language: Java (java)

First, we created a bucket of a certain size. Next, we used the bucket to read bytes from the InputStream and write them on the OutputSteam.

Using Java transferTo method

Java provides a concise abstraction to achieve this. Using the transferTo method on the InputStream we can avoid the buffers and iterations logic.

Next is example of writing to OutputStream.

try (OutputStream outputStream = new FileOutputStream(outputPath)) {
    inputStream.transferTo(outputStream);
}Code language: Java (java)

Using Guava

The Guava Library is popular for various abstraction and utility methods. We can use ByteStreams class to make the copy.

Next is Guava example of writing InputStream bytes to OutputStream.

try (OutputStream outputStream = new FileOutputStream(outputPath)) {
    ByteStreams.copy(inputStream, outputStream);
}Code language: Java (java)

Using Apache Commons IO

Finally, we create OutputStream from an InputStream using Apache Commons IO.

try (OutputStream outputStream = new FileOutputStream(outputPath)) {
    IOUtils.copy(inputStream, outputStream);
}Code language: Java (java)

Summary

In this tutorial we covered How to Copy an InputStream to an OutputStream in Java. We covered examples of using Core Java and using Java abstraction. Lastly, we used third party libraries – Guava and Apache Commons IO to transfer an InputStream to an OutputStream. For more on Java, please visit Java Tutorials.