zoukankan      html  css  js  c++  java
  • java基础:IO流之缓冲流

    简介

    缓冲流属于处理流的一种

    缓冲流有四种:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter

    缓冲流可以提高文件读写的速度

    BufferedInputStream和BufferedOutputStream

    先使用非缓冲流测试复制1个G的文件

    File src = new File("C:\Users\wj\Desktop\01.ts");
    File dest = new File("C:\Users\wj\Desktop\01.1.ts");
    long start = System.currentTimeMillis();
    try(FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(dest)){
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1){
            fos.write(buffer, 0, len);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    

    耗费11s

    image-20210422114638449

    BufferedInputStream和BufferedOutputStream的使用与FileInputStream和FileOutputStream差不多,这里不详细介绍。

    这里jdk底层使用的装饰器设计模式,我们用BufferedInputStream包装FileInputStream即可,BufferedOutputStream也是如此。

    File src = new File("C:\Users\wj\Desktop\01.ts");
    File dest = new File("C:\Users\wj\Desktop\01.2.ts");
    long start = System.currentTimeMillis();
    try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest))){
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1){
            bos.write(buffer, 0, len);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    

    两秒多就可以完成:效率提升十分明显

    image-20210422114837147

    内部原理:内部提供了一个缓存区

    BufferedReader、BufferedWriter

    测试按行读取并复制文本文件:

    File src = new File("斗破苍穹.txt");
    File dest = new File("斗破苍穹-buffered.txt");
    long start = System.currentTimeMillis();
    try(BufferedReader br = new BufferedReader(new FileReader(src));
        BufferedWriter bw = new BufferedWriter(new FileWriter(dest))){
        String line ;
        //按行读取
        while ((line = br.readLine()) != null){
            bw.write(line);
            bw.newLine();//换行
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    

    复制出来的文件也是没有问题的

    image-20210422121056302

  • 相关阅读:
    学到的一些函数和好的方法
    MVC 捋一遍(3)
    MVC 捋一遍(2)
    mvc 安装ef遇到的各种奇葩问题
    MVC 捋一遍(1)
    httpServletRequest.getCharacterEncoding()取出来是个null,怎么办?
    spring常用注解
    覆盖io.spring.platform管理的版本号
    下拉点击跳到指定链接(类同友情链接)
    EditPlus 3.7激活码注册码
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14689012.html
Copyright © 2011-2022 走看看