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

后端 未结 23 2495
粉色の甜心
粉色の甜心 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 03:07

    The JDK uses the same code so it seems like there is no "easier" way without clunky third party libraries (which probably don't do anything different anyway). The following is directly copied from java.nio.file.Files.java:

    // buffer size used for reading and writing
    private static final int BUFFER_SIZE = 8192;
    
    /**
      * Reads all bytes from an input stream and writes them to an output stream.
      */
    private static long copy(InputStream source, OutputStream sink) throws IOException {
        long nread = 0L;
        byte[] buf = new byte[BUFFER_SIZE];
        int n;
        while ((n = source.read(buf)) > 0) {
            sink.write(buf, 0, n);
            nread += n;
        }
        return nread;
    }
    

提交回复
热议问题