Java中IOUtils.copy(in,out)方法,关于缓冲byte[]buffer的问题


内部的缓冲byte[]buffer,定义的大小为4096,如果要写的io流内容超过这个大小呢
贴个源码:


 public static int copy(InputStream input, OutputStream output) throws IOException {
    long count = copyLarge(input, output);
    if (count > Integer.MAX_VALUE) {
        return -1;
    }
    return (int) count;
}

public static long copyLarge(InputStream input, OutputStream output)
        throws IOException {
    return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);//大小为4096
}

public static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
        throws IOException {
    long count = 0;
    int n = 0;
    while (EOF != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        count += n;
    }
    return count;
}

也没看见对buffer有什么别的处理呀?如果buffer大小不够呢?

java IO

tusoma 9 years, 8 months ago

你觉得缓冲区应该有多大?如果你要复制一个几百MB的文件,那缓冲区也要有几百MB大小?

缓冲区就像一个推车,来往于i/o端,运送数据,作用就是减少了来往的次数,减少了开销。

三森二十七木 answered 9 years, 8 months ago

关键看这里 while (EOF != (n = input.read(buffer)))
文档里是这么说的:

public int read(byte[] b) throws IOException

从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数。在输入数据可用、检测到文件末尾或者抛出异常前,此方法一直阻塞。
如果 b 的长度为 0,则不读取任何字节并返回 0;否则,尝试读取至少一个字节。如果因为流位于文件末尾而没有可用的字节,则返回值 -1;否则,至少读取一个字节并将其存储在 b 中。
将读取的第一个字节存储在元素 b[0] 中,下一个存储在 b[1] 中,依次类推。 读取的字节数最多等于 b 的长度。 设 k 为实际读取的字节数;这些字节将存储在 b[0] 到 b[k-1] 的元素中,不影响 b[k] 到 b[b.length-1] 的元素。
类 InputStream 的 read(b) 方法的效果等同于:
read(b, 0, b.length)

就是说每次最多读4096字节,如果多于4096字节会由while循环读取多次

7824902 answered 9 years, 8 months ago

Your Answer