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

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

    This is my best shot!!

    And do not use inputStream.transferTo(...) because is too generic. Your code performance will be better if you control your buffer memory.

    public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException {
        byte[] read = new byte[buffer]; // Your buffer size.
        while (0 < (buffer = in.read(read)))
            out.write(read, 0, buffer);
    }
    

    I use it with this (improvable) method when I know in advance the size of the stream.

    public static void transfer(int size, InputStream in, OutputStream out) throws IOException {
        transfer(in, out,
                size > 0xFFFF ? 0xFFFF // 16bits 65,536
                        : size > 0xFFF ? 0xFFF// 12bits 4096
                                : size < 0xFF ? 0xFF // 8bits 256
                                        : size
        );
    }
    

提交回复
热议问题