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

后端 未结 23 2493
粉色の甜心
粉色の甜心 2020-11-22 02:10

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. Obviou

23条回答
  •  误落风尘
    2020-11-22 02:54

    Java 9

    Since Java 9, InputStream provides a method called transferTo with the following signature:

    public long transferTo(OutputStream out) throws IOException
    

    As the documentation states, 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 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

    So in order to write contents of a Java InputStream to an OutputStream, you can write:

    input.transferTo(output);
    

提交回复
热议问题