概述
什么是缓冲流
缓冲流,也叫 高效流
,是对 4个 基本的 File *** 流的增强
所以也是 4个流,按照数据类型分类: 字节缓冲流: BufferedInputStream , BufferedOutputStream,字符缓冲流: BufferedReader , BufferedWriter
基本原理
缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统 IO 次数,从而提高读写的效率。
字节缓冲流
构造方法
- public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。
- public BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流。
//创建字节缓冲输入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("xhh.txt")); //创建字节缓冲输出流 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("xhh.txt"));
效率测试
直接使用 FileInputStream 与 FileOutStream 复制文件
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); FileInputStream fis = new FileInputStream("D:/apache-echarts-4.6.0-incubating-src.zip"); FileOutputStream fos = new FileOutputStream("newApache.zip"); int len; byte[] b = new byte[1024]; while ((len = fis.read(b)) != -1){ fos.write(b); } fis.close(); fos.close(); long end = System.currentTimeMillis(); System.out.println("时间:"+(end-start)); } // 49
使用缓冲流复制文件
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/apache-echarts-4.6.0-incubating-src.zip")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("newApache.zip")); int len; byte[] b = new byte[1024]; while ((len = bis.read(b)) != -1){ bos.write(b); } bis.close(); bos.close(); long end = System.currentTimeMillis(); System.out.println("时间:"+(end-start)); } // 25
字符缓冲流
构造方法
- public BufferedReader(Reader in)
- public BufferedWriter(Writer out)
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("xhh.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("xhh.txt")); }
特有方法
- BufferedReader
- public String readLine():读一行文字
- BufferedWriter
- public void newLine() :写一行行分隔符,由系统属性定义符号
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("xhh.txt")); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); }
public static void main(String[] args) throws Exception { BufferedWriter br = new BufferedWriter(new FileWriter("out.txt")); br.write("小灰"); br.newLine(); br.write("灰"); br.newLine(); br.close(); }