java io 缓冲_【Java】IO流--缓冲流--Buffered

缓冲流

82244022e93fe2ab3de3b58400387bae.png

1.读文件和写文件都使用了缓冲区,减少了读写次数,从而提高了效率

2.当创建这两个缓冲流的对象时,会创建内部缓冲数组,缺省使用32字节大小的缓冲区

3.当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区

4.当写入数据时,首先写入缓冲区,当缓冲区满时,其中的数据写入所连接的输出流。使用方法flush()可以强制将缓冲区的内容全部写入输出流。

5.关闭流的顺序和打开流的顺序相反。只要关闭高层流即可,关闭高层流其实关闭了底层节点流。

6.Flush的使用:手动将buffer中内容写入文件。

————————————————

版权声明:本文为CSDN博主「彭浩95」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_33193871/article/details/88196322

字节缓冲流

importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;public classTestBufferedCopy {public static voidmain(String[] args) {

BufferedInputStream bis=null;

BufferedOutputStream bos=null;try{

bis= new BufferedInputStream(new FileInputStream("F://test.txt"));

bos= new BufferedOutputStream(new FileOutputStream("F://copy2.txt"));byte[] buf=new byte[1024];int len=0;while((len=bis.read(buf))!=-1) {

bos.write(buf,0, len);

bos.flush();

}

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{if(bos!=null) {try{

bos.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}if(bis!=null) {try{

bis.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

字符缓冲流

BufferedReader

readLine()

每次读取一行数据

BufferedWriter

newLine()

写入一个换行符

importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileNotFoundException;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;public classTestBuffered {public static voidmain(String[] args) {

BufferedReader br=null;

BufferedWriter bw=null;try{

br= new BufferedReader(new FileReader("F://test.txt"));

bw= new BufferedWriter(new FileWriter("F://copy3.txt"));

String str=null;while((str=br.readLine())!=null) {

bw.write(str);

bw.newLine();

bw.flush();

}

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{if(bw!=null) {try{

bw.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}if(br!=null) {try{

br.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值