先看一段关于Buffer的英文:
Buffer can speed up IO quite a bit.
The BufferedInputStream class provides buffering to your input streams.
With both disk and network streams, the optimal buffer size may also depend on the concrete hardware in the computer. If the hard disk is anyways reading a minimum of 4KB at a time, it's stupid to use less than a 4KB buffer. It is also better to then use a buffer size that is a multiple of 4KB.
The main difference between BufferedReader and BufferedInputStream is that BufferedReader reads characters (text), whereas the BufferedInputStream reads raw bytes.
The BufferedWriter adds one extra method though: The newLine() method which can write a new-line character to the underlying Writer. In addition, you may need to call flush() if you need to be absolutely sure that the characters written until now is flushed out of the buffer and **onto **the network or disk.
为什么在IO中,buffer不可或缺?
我们知道,数据可能存储在不同的介质中,比如寄存器,内存,硬盘等。不同介质中的数据需要通信,而不同介质的数据存取速度往往差异很大,这样就会造成快者等待慢者的现象。为了解决这种速度不匹配的问题,buffer就大展身手了。
比如读硬盘,最小读取数据单元是4KB,那么就会一次读取4KB的整数倍,放在buffer中,这样内存就不必须频繁读硬盘了。这就是预读取的思想。
不仅仅是读,写操作也会用到buffer,也是为了频繁地写。写操作有一个特殊的函数flush(),用于把buffer中的数据刷出去,写到硬盘或者网络中去。
基于这种设计,CPU会把常用数据从内存中放到自己的缓存中,操作系统会把常用数据从硬盘读取到内存。