Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

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. 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);

}

1 Answer

0 votes
by (46k points)

Use InputStream it presents a method called transferTo with the following impression:

public long transferTo(OutputStream out) throws IOException

From the documentation, 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 the 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, highly inputs and output stream specific, and therefore not specified

So in order to reproduce contents of a Java InputStream to an OutputStream, you need to address:

input.transferTo(output);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...