patternjavaCritical
Easy way to write contents of a Java InputStream to an OutputStream
Viewed 0 times
javainputstreamoutputstreamcontentswritewayeasy
Problem
I was surprised to find today that I couldn't track down any simple way to write the contents of an
So, given an
InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).So, given an
InputStream in and an OutputStream out, is there a simpler way to write the following?byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}Solution
Java 9
Since Java 9,
As the documentation states,
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
Since Java 9,
InputStream provides a method called transferTo with the following signature:public long transferTo(OutputStream out) throws IOExceptionAs 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);Code Snippets
public long transferTo(OutputStream out) throws IOExceptioninput.transferTo(output);Context
Stack Overflow Q#43157, score: 271
Revisions (0)
No revisions yet.