JAVA IO—缓冲区(Buffered)
一.BufferedInputStream
BufferedInputStream提供缓冲机制以提高IO性能。在创建BufferedInputStream时,会创建内部缓冲区数组。当跳过或读取流中的字节时,缓冲区会自动从包含的输入流中重新填充。
public static void main(String args[]) {
try {
FileInputStream fileStream = new FileInputStream("D:\\test.txt");
BufferedInputStream bufferStream = new BufferedInputStream(fileStream, 1024);
int ret = bufferStream.read();
while (ret != -1) {
System.out.print((char) ret);
ret = bufferStream.read();
}
bufferStream.close();
fileStream.close();
} catch (Exception e) {
System.out.println(e);
}
}
二.BufferedOutputStream
BufferedOutputStream性质与BufferedInputStream一样,只不过它是输出的缓冲区。
public static void main(String args[]) throws Exception {
FileOutputStream fileOutStream = new FileOutputStream("D:\\test.txt");
BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream, 1024);
String str = "hello world,hello world";
byte b[] = str.getBytes();
bufferOutStream.write(b);
bufferOutStream.flush();
bufferOutStream.close();
fileOutStream.close();
}
三.缓冲区最近大小
要找到最佳缓冲区大小,首先要找出硬盘写入的块大小,然后设置缓冲区为块大小的倍数。如:硬盘一次最写入4KB,那么最好使用4KB倍数的缓冲区大小。