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. Here is an example:

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

inputStream.close();
outputStream.close();

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, you can use the java.nio.file.Files class to copy the contents of an input stream to an output stream, using the copy method:

InputStream inputStream = // get the input stream
OutputStream outputStream = // get the output stream

Files.copy(inputStream, outputStream);

inputStream.close();
outputStream.close();

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