IO缓冲区(buffer)的原理及作用

缓冲区就是内存里的一块区域,把数据先存内存里,然后一次性写入,类似于数据库的批量操作,这样大大提高高了数据的读写速率。

现在的外设控制器都有自己的缓冲池,如磁盘和网卡,通过缓冲IO的方式读取时,如BufferedInputStream里就有个buf块,CPU可把外设里的缓冲池available的字节块整块读入该buf内存。

以下是分别是利用缓冲区进行读写和复制操作的使用代码


import java.io.*;
//缓冲区为了提高流的操作效率,所以在创建缓冲区之前必须先有流对象
public class Bufwritered {
public static void main(String[] args){
//创建一个字符写入流对象
FileWriter fw;
BufferedWriter bufw = null;
try{
fw = new FileWriter("buf.txt");
bufw = new BufferedWriter(fw);
bufw.write("abcde");
bufw.newLine();//缓冲区提供的换行符
}
catch(IOException e){
throw new RuntimeException("读写失败");
}
finally{
if(bufw!=null)
try{
bufw.close();
}
catch(IOException e)
{
}
}
}
}


字符读取流缓冲区

package com.itheima;
/*
 * 字符读取流缓冲区
 */
import java.io.*;
public class Buffreader {
public static void main(String[] args){
FileReader fr;
BufferedReader bufr = null;
try{
fr = new FileReader("buf.txt");
bufr = new BufferedReader(fr);
String line =null;
while((line=bufr.readLine())!=null){
System.out.println(line);
}}
catch(IOException e){
throw new RuntimeException("读写失败");
}
finally{

try{
if(bufr!=null)
bufr.close();
}
catch(IOException e){

}
}

}
}


通过一个缓冲区复制一个文件

package com.itheima;
/*
 * 通过一个缓冲区复制一个文件
 */
import java.io.*;
public class copy {
public static void main(String[] args){
BufferedReader bufr = null;
BufferedWriter bufw = null;
try{
bufr=new BufferedReader(new FileReader("buf.java"));
bufw=new BufferedWriter(new FileWriter("buf.txt"));
String line=null;
if((line=bufr.readLine())!=null){
bufw.write(line);
bufw.newLine();
bufw.flush();
}
}
catch(IOException e){
throw new RuntimeException("读写失败");

}
finally{
try{
if(bufr!=null)
bufr.close();
}
catch(IOException e){
throw new RuntimeException("关闭写失败");
}
try{
if(bufw!=null)
bufw.close();
}
catch(IOException e){
throw new RuntimeException("关闭读失败");
}
}
}
}
---------------------

原文:https://blog.csdn.net/cainiaoheng/article/details/46634719

猜你喜欢

转载自blog.csdn.net/Zhi_19950628/article/details/88397337