I was surprised to find today that I couldn\'t track down any simple way to write the contents of an InputStream
to an OutputStream
in Java. Obviou
Since Java 9, InputStream
provides a method called transferTo
with the following signature:
public long transferTo(OutputStream out) throws IOException
As the documentation states, transferTo
will:
Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read. On return, this input stream will be at end of stream. This method does not close either stream.
This method may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted during the transfer, is highly input and output stream specific, and therefore not specified
So in order to write contents of a Java InputStream
to an OutputStream
, you can write:
input.transferTo(output);