首页 > 代码库 > 缓冲输入输出流[也叫包装流] BufferedInputStream,BufferedOutputStream,BufferedReader和BufferedWriter
缓冲输入输出流[也叫包装流] BufferedInputStream,BufferedOutputStream,BufferedReader和BufferedWriter
字符缓冲流: 开发时候建议使用缓冲流,速度和效率更快。
BufferedReader的api部分:
BufferedInputStream 部分api: 可以看出
BufferedInputStream是没有readLine()方法。更多具体,请自行查看api文档
package cn.bean.demo.io.buffer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class BufferedReaderTest { public static void main(String[] args) { testReadWrite(); } static void testReadWrite(){ try ( Reader read = new FileReader("String1.txt"); BufferedReader buff = new BufferedReader(read); Writer writer = new FileWriter("String2.txt"); BufferedWriter buffWrite = new BufferedWriter(writer); ) { //每次读取的数据放入到缓冲区 char[] ch=new char[10]; // 每次读取的时候放入到缓冲区的实际字符个数 int len=0; while((len=buff.read(ch))!=-1){ buffWrite.write(ch, 0, len);; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static void testReadWriteLine(){ try ( Reader read = new FileReader("String1.txt"); BufferedReader buff = new BufferedReader(read); Writer writer = new FileWriter("String2.txt"); BufferedWriter buffWrite = new BufferedWriter(writer); ) { String content=null; int i=0; while((content=buff.readLine())!=null){ if(i!=0){ //第一次不换行,当第二次写的时候换行 buffWrite.write("\n"); } buffWrite.write(content); i++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
再看一下字符缓冲流:
package cn.bean.demo.io.buffer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class BufferedInputStreamTest { public static void main(String[] args) { testReadWriteReadLine(); } static void testReadWriteReadLine() { try (InputStream in = new FileInputStream("String1.txt"); BufferedInputStream buffer = new BufferedInputStream(in); OutputStream out = new FileOutputStream("String2.txt"); BufferedOutputStream bufferWrite = new BufferedOutputStream(out);) { //BufferedInputStream没有readLine方法 //创建一个用来存放每次读取的数据的缓冲区 byte[] b=new byte[20]; //每次读取,并放入到缓冲区的实际字符个数 int len=0; while((len=buffer.read(b))!=-1){ bufferWrite.write(b, 0, len); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
缓冲输入输出流[也叫包装流] BufferedInputStream,BufferedOutputStream,BufferedReader和BufferedWriter
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。