首先要明确一个概念:java
对文件或其余目标频繁的读写操做,效率低,性能差。数组
使用缓冲流的好处是:可以高效的读写信息,原理是先将数据先缓冲起来,而后一块儿写入或者读取出来。缓存
对于字节:性能
BufferedInputStream:为另外一个输入流添加一些功能,在建立BufferedInputStream时,会建立一个内部缓冲区数组,用于缓冲数据。spa
BufferedOutputStream:经过设置这种输出流,应用程序就能够将各个字节写入底层输出流中,而没必要针对每次字节写入调用底层系统。code
对于字符:blog
BufferedReader:将字符输入流中读取文本,并缓冲各个字符,从而实现字符、数组、和行的高效读取。字符串
BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。get
代码示例:it
package IODemo; import java.io.*; /* 缓冲的目的: 解决在写入文件操做时,频繁的操做文件所带来的性能下降的问题 BufferedOutStream 内部默认的缓冲大小是 8Kb,每次写入储存到缓存中的byte数组中,当数组存尽是,会把数组中的数据写入文件 而且缓存下标归零 */ public class BufferedDemo { //使用新语法 会在try里面帮关掉这个流 private static void BuffRead2(){ File file = new File("d:\\test\\t.txt"); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){ byte[] bytes = new byte[1024]; int len = -1; while ((len = bis.read(bytes))!=-1){ System.out.println(new String(bytes,0,len)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void BuffRead(){ File file = new File("d:\\test\\t.txt"); try { InputStream in = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(in); byte[] bytes = new byte[1024]; int len = -1; while ((len = bis.read(bytes))!=-1){ System.out.println(new String(bytes,0,len)); } bis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void BuffWrite(){ File file = new File("d:\\test\\t.txt"); try { OutputStream out = new FileOutputStream(file); //构造一个字节缓冲流 BufferedOutputStream bos = new BufferedOutputStream(out); String info = "我是落魄书生"; bos.write(info.getBytes()); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // BuffWrite(); BuffRead2(); } }