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

  • 相关阅读:
    MySQL的四种事务隔离级别
    线上CPU飚高(死循环,死锁...)
    Tomcat7 调优及 JVM 参数优化
    tomcat8.5配置高并发
    Tomcat 8.5 基于 Apache Portable Runtime(APR)库性能优化
    android 高德地图 轨迹平滑处理
    android高德地图绘制线 渐变处理
    按下home键,重新打开,应用重启
    小米9屏下指纹判断
    android 9.0以上charles https抓包
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14689012.html
Copyright © 2011-2022 走看看