我们按功能可以将IO流分为节点流与处理流
节点流:可以直接从数据源或目的地读写数据
处理流(装饰流):不直接连接到数据源或目的地,是其他流(必须包含节点流)进行封装。目的主要是简化操作和提高性能。
Buffered流的引入
当我们使用节点流来传输数据时,节点流单次传输的数据太少,会频繁读写硬盘,这使得整体速度不高,就像蚂蚁搬家。
这时我们引入处理流Buffered流,就好像找来一辆卡车来搬家,单次运输的数据多了,访问硬盘的次数少了,速度得到提升。
copy文件示例
不引入Buffered流copy一个600m的文件所需要的时间
import java.io.*;
public class IOTest01
{
public static void main(String[] args)
{
//文件源
String src = "1.rar";
String dest = "1_cp.rar";
//计算copy花费的时间
long l1 = System.currentTimeMillis();
copy(src,dest);
long l2 = System.currentTimeMillis();
long time = l2-l1;
System.out.println(time);
}
public static void copy(String srcPath,String destPath){
//选择流
//操作
try(InputStream is = new FileInputStream(srcPath);
OutputStream os = new FileOutputStream(destPath)){
byte[] flush = new byte[1024*10];
int len = -1;
while((len = is.read(flush))!=-1){//读入
os.write(flush,0,len);//写出
}
os.flush();//刷新
}catch(IOException e){
e.printStackTrace();
}
}
}
输出时间:
引入Buffered流后
标签:Buffered,12,String,BufferedInputStream,OutputStream,flush,new,copy,节点
来源: https://www.cnblogs.com/Scorpicat/p/11921536.html