W3docs

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

One way to write the contents of a Java InputStream to an OutputStream is to use the read and write methods of the InputStream and OutputStream classes.

One way to write the contents of a Java InputStream to an OutputStream is to use the read and write methods of the InputStream and OutputStream classes. Here is an example:


try (InputStream inputStream = // get the input stream;
     OutputStream outputStream = // get the output stream) {
  byte[] buffer = new byte[1024];
  int length;
  while ((length = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, length);
  }
}

This will read the contents of the input stream in blocks of 1024 bytes and write them to the output stream, until the end of the input stream is reached.

Alternatively, since Java 9, you can use the transferTo method on InputStream for a shorter and simpler approach:


try (InputStream inputStream = // get the input stream;
     OutputStream outputStream = // get the output stream) {
  inputStream.transferTo(outputStream);
}

This is a shorter and simpler way to copy the contents of an input stream to an output stream.