Java中IOUtils.copy(in,out)方法,关于缓冲byte[]buffer的问题
PHP中文网
PHP中文网 2017-04-17 12:01:20
0
2
939

内部的缓冲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大小不够呢?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
左手右手慢动作

The key is herewhile (EOF != (n = input.read(buffer)))
This is what the documentation says:

public int read(byte[] b) throws IOException

Read a certain number of bytes from the input stream and store them in the buffer array b. Returns the actual number of bytes read as an integer. This method blocks until input data is available, end-of-file is detected, or an exception is thrown.
If the length of b is 0, no bytes are read and 0 is returned; otherwise, an attempt is made to read at least one byte. If no bytes are available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored in b.
Store the first byte read in element b[0], the next in b[1], and so on. The number of bytes read is at most equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements from b[0] to b[k-1] and do not affect b[k] to b[b.length -1] elements.
The effect of the read(b) method of class InputStream is equivalent to:
read(b, 0, b.length)

That is to say, a maximum of 4096 bytes can be read each time. If more than 4096 bytes are read, the while loop will read multiple times

洪涛

How big do you think the buffer should be? If you want to copy a file of several hundred MB, does the buffer also need to be several hundred MB in size?

The buffer is like a cart that travels to and from the I/O side to transport data. Its function is to reduce the number of transactions and reduce overhead.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!