This article presents different ways of Writing an InputStream to an OutputStream by using Apache Commons IO, Guava, and Core Java.
Tutorial Contents
Overview
In this tutorial, we will cover various examples of writing the contents of a Java InputStream to OutputStream. First, we will begin with the 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
The idea is to create a buffer or a bucket, fill the bucket iteratively with an optimal number of bytes, and copy the bytes into the other stream until all the buffers are copied.
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.
Please note that the larger the buffer size, the faster the copy and the larger the footprint on memory. Hence, we need to trade off between performance and memory.
Using Java transferTo method
Alternatively, Java provides a concise abstraction to achieve this. Using the transferTo
method on the InputStream we can avoid buffers and iteration logic.
Next is example of writing to OutputStream.
try (OutputStream outputStream = new FileOutputStream(outputPath)) {
inputStream.transferTo(outputStream);
}
Code language: Java (java)
This method provides an optimal solution. However, if we need more control over the performance, we can use the buffer copy approach.
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’s 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 discussed how to copy an InputStream to an OutputStream in Java. We provided examples using Core Java as well as Java abstractions. Additionally, we explored third-party libraries such as Guava and Apache Commons IO for transferring data from an InputStream to an OutputStream. For more on Java, please visit Java Tutorials.