谈到java BIO中的性能优化,大部分人都会说使用BufferedInputStream BufferedOutputStream,理由是IO是跟硬件交互,是耗时操作,使用BufferedInputStream减少IO交互次数能大量提升IO性能。
查看BufferedInputStream 源码,BufferedInputStream 有一个缓存数组
protected volatile byte buf[];
缓存数组大小默认是8192,也就是8K,(网上好多文章都是8M....文章一大抄 0.0)
private static int defaultBufferSize = 8192;
调用BufferedInputStream的读取方法时,会先判断缓存数组有没有可用数据,如果没有会先调用fill()方法将数据从硬盘加载到缓存中,然后从缓存数据中取数据返回。(调用fill前有个判断(第八行)如果要求的数据长度比缓存的数组容器长度(不是指有效缓存长度)大,那将直接从硬盘读取加载,不再走BufferedInputStream的内存缓存)
private int read1(byte[] b, int off, int len) throws IOException {
int avail = count - pos;
if (avail <= 0) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, do not bother to copy the
bytes into the local buffer. In this way buffered streams will