1. Introduction
In this article, we are going to present several ways to convert InputStream to OutpuStream in Java. To perform this operation we will use classes available in plain Java and libraries such as Guava
and Apache Commons IO
.
For more Java I/O related articles check the following links:
2. Copy InputStream to OutputStream using OutputStream.write(...)
method
Below Java 8 we can simply rewrite bytes from InputStream
to OutputStream
using read(...)
and write(...)
method like in the following example:
In this approach, we used read(...)
method available on InputStream
to read bytes from the byte-based stream. In a loop, we write read bytes directly to the OutputStream
using write(...)
method.
3. Convert InputStream to OutputStream using InputString.transferTo(...)
method available in JDK 9
Let's take a look at the next example that makes the use of the transferTo(...)
method available from Java 9.
Using InputStream.transferTo(...)
allows us to transfer bytes from InputStream
to the OutputStream
in a one line of code.
4. InputStream to OutputStream using Apache Commons IO
library
The Apache Commons IO
library was designed with IO operations in mind. It comes with many utility methods, and we can use one of them to copy bytes from a byte-based stream to the OutputStream
.
In this example, we make use of IOUtils.copy(...)
method that copy bytes from InputStream
to the OutputStream
transparently.
5. Convert InputStream to OutputStream with Guava
Guava
is another library that we can use to write bytes from InputStream
to the OutputStream
. Let's check the following example:
Guava
provides ByteStreams.copy(...)
method very similar to Apache Commons IO
s IOUtils.copy(...)
. The logic behind these two methods is the same.
6. Conclusion
In this article, we presented various ways to convert InputStream
to the OutputStream
. This operation comes down to read bytes from the InputStream
and write them to the OutputStream
in the same order.
Examples used in this article are available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}