本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.缓冲流说明
缓冲流,也叫高效流,是对4个基本的FileXxx 流的增强,所以也是4个流,按照数据类型分类:
-
字节缓冲流:BufferedInputStream,BufferedOutputStream
-
字符缓冲流:BufferedReader,BufferedWriter
缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
2.字符流和缓冲字符流的对比
publicclassIOTest{
publicstaticvoidmain(String[]args)throwsIOException{
//数据准备
dataReady();
Filedata=newFile("C:/Mu/data.txt");
Filea=newFile("C:/Mu/a.txt");
Fileb=newFile("C:/Mu/b.txt");
Filec=newFile("C:/Mu/c.txt");
longstart=System.currentTimeMillis();
copy(data,a);
longend=System.currentTimeMillis();
longstart2=System.currentTimeMillis();
copyChars(data,b);
longend2=System.currentTimeMillis();
longstart3=System.currentTimeMillis();
bufferedCopy(data,c);
longend3=System.currentTimeMillis();
System.out.println("普通字节流1耗时:"+(end-start)+"ms,文件大小:"+a.length()/1024+"kb");
System.out.println("普通字节流2耗时:"+(end2-start2)+"ms,文件大小:"+b.length()/1024+"kb");
System.out.println("缓冲字节流耗时:"+(end3-start3)+"ms,文件大小:"+c.length()/1024+"kb");
}
//普通字符流不使用数组
publicstaticvoidcopy(Filein,Fileout)throwsIOException{
Readerreader=newFileReader(in);
Writerwriter=newFileWriter(out);
intch=0;
while((ch=reader.read())!=-1){
writer.write((char)ch);
}
reader.close();
writer.close();
}
//普通字符流使用字符流
publicstaticvoidcopyChars(Filein,Fileout)throwsIOException{
Readerreader=newFileReader(in);
Writerwriter=newFileWriter(out);
char[]chs=newchar[1024];
while((reader.read(chs))!=-1){
writer.write(chs);
}
reader.close();
writer.close();
}
//缓冲字符流
publicstaticvoidbufferedCopy(Filein,Fileout)throwsIOException{
BufferedReaderbr=newBufferedReader(newFileReader(in));
BufferedWriterbw=newBufferedWriter(newFileWriter(out));
Stringline=null;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
br.close();
}
//数据准备
publicstaticvoiddataReady()throwsIOException{
StringBuildersb=newStringBuilder();
for(inti=0;i<600000;i++){
sb.append("abcdefghijklmnopqrstuvwxyz");
}
OutputStreamos=newFileOutputStream(newFile("C:/Mu/data.txt"));
os.write(sb.toString().getBytes());
os.close();
System.out.println("完毕");
}
}
运行结果:
普通字符流1耗时:1337ms,文件大小:15234kb 普通字符流2耗时:82ms,文件大小:15235kb 缓冲字符流耗时:205ms,文件大小:15234kb
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容