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

后端 未结 23 2731
粉色の甜心
粉色の甜心 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:49

    PipedInputStream and PipedOutputStream should only be used when you have multiple threads, as noted by the Javadoc.

    Also, note that input streams and output streams do not wrap any thread interruptions with IOExceptions... So, you should consider incorporating an interruption policy to your code:

    byte[] buffer = new byte[1024];
    int len = in.read(buffer);
    while (len != -1) {
        out.write(buffer, 0, len);
        len = in.read(buffer);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }
    

    This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time.

提交回复
热议问题