
为了使程序的读写速度得到提升,设置的缓冲区不是为了阻碍,而是在这个区域内较少流的次数,工作量少了自然效率会进行提高。在缓冲流中有两种类型,分别是字节缓冲流和字符缓冲流,它们都有各自的构造方法,在我们对这些基本理论学习之后,分别进入下一步的各自缓冲流实例学习。
1.字节缓冲流
构造方法
1 2 | public BufferedInputStream(InputStream in ) :创建一个新的缓冲输入流。
public BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流。
|
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Demo03 {
public static void main(String[] args) throws IOException {
Long start =System.currentTimeMillis();
FileInputStream fis= new FileInputStream( "E:\\shipin\\1.rar" );
BufferedInputStream bis= new BufferedInputStream(fis);
FileOutputStream fos= new FileOutputStream( "D:\\java\\shipin.rar" );
BufferedOutputStream bos= new BufferedOutputStream(fos);
byte[] bytes= new byte[1024];
int len=0;
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
long end=System.currentTimeMillis();
bis.close();
bos.close();
System.out.println( "479MB的压缩包字节缓冲流复制的时间为" +(end-start)+ "毫秒值!" );
}
}
|
2.字符缓冲流
构造方法
1 2 | public BufferedReader(Reader in ) :创建一个 新的缓冲输入流。
public BufferedWriter(Writer out): 创建一个新的缓冲输出流。
|
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Copy {
public static void main(String[] args) throws IOException {
FileReader fr= new FileReader( "D:\\java\\hello.txt" );
BufferedReader br= new BufferedReader(fr);
FileWriter fw= new FileWriter( "D:\\java\\nihao.txt" );
BufferedWriter bw= new BufferedWriter(fw);
String line= null ;
while ((line=br.readLine())!= null ){
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
}
|
以上就是java缓冲流中两种类型的分享,在不同的条件下,对选择对应的缓冲流进行操作,学会后就赶紧进入实战代码练练手吧。
(推荐操作系统:windows10系统、java10版,thinkpad t480电脑。)