Java – Easy way to write contents of a Java InputStream to an OutputStream


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 =;
while (len != -1) {
    out.write(buffer, 0, len);
    len =;

Best Answer

As WMR mentioned, from Apache has a method called copy(InputStream,OutputStream) which does exactly what you're looking for.

So, you have:

InputStream in;
OutputStream out;
out.close(); your code.

Is there a reason you're avoiding IOUtils?