Copying an InputStream
Description
After Java 9, you can copy an InputStream more easily using the transferTo method in InputStream.
The JDK description for this method is:
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. If an I/O error occurs reading from the input stream or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the input stream may not be at end of stream and one, or both, streams may be in an inconsistent state. It is strongly recommended that both streams be promptly closed if an I/O error occurs.
Params: out – the output stream, non-null Returns: the number of bytes transferred
From the description above, the most important sentence is: This method does not close either stream. This is the best reason to choose it for copying InputStreams, because reading an InputStream closes the stream, making it non-reusable.
Code Section
Here's the code for copying an InputStream:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream = resourceLoader.getResource("classpath:test.txt").getInputStream();
inputStream.transferTo(outputStream);
InputStream firstClone = new ByteArrayInputStream(baos.toByteArray());
InputStream secondClone = new ByteArrayInputStream(baos.toByteArray());
First create an outputStream, then get the InputStream we need from the specified path. Then we call this InputStream's transferTo to write bytes to the created outputStream. Now we can use this outputStream to create new InputStreams without closing the original inputStream.