zoukankan      html  css  js  c++  java
  • 详解 高效字节流

    (请观看本人博文——《详解 字节流》

    高效字节流:

    其实,以本人上面的构造缓冲区来缩短运行时间的思想,Java有一个专门封装好的类,用于处理对大文件的读和写的操作 ——
    BufferedInputStream 和 BufferedOutputStream:


    @


    BufferedOutputStream:

    (高效字节输出流)

    现在,本人来讲解下这个类的构造方法

    BufferedOutputStream(OutputStream out)
    BufferedOutputStream(OutputStream out, int size)
    (注:参数size决定了缓冲区的大小,
    如果不写的话,则默认为8192字节)

    至于常用API,就是write(),参数和FileOutputStream的write()方法的参数一样。


    BufferedInputStream:

    (高效字节输入流)

    现在,本人来讲解下这个类的构造方法

    BufferedInputStream(InputStream out)
    BufferedInputStream(InputStream out, int size)
    (注:参数size决定了缓冲区的大小,
    如果不写的话,则默认为8192字节)

    至于常用API,就是read(),参数和FileInputStream的read()方法的参数一样。


    那么,现在,本人就利用这两个类,来实现下文件的复制

    package edu.youzg.about_io.about_file.core;
    
    import java.io.*;
    
    public class Test {
    
        public static void main(String[] args) {
            //高效的字节输入输出流
            BufferedInputStream bfr = null;
            BufferedOutputStream bfw = null;
            try {
                bfr = new BufferedInputStream(new FileInputStream("test.mp3"));
                bfw = new BufferedOutputStream(new FileOutputStream("copyView3.mp3"));
                int len=0;
                byte[] bytes = new byte[1024 * 8];
                long start = System.currentTimeMillis();
                while ((len=bfr.read(bytes))!=-1){
                    bfw.write(bytes,0,len);
                }
                long end = System.currentTimeMillis();
                System.out.println((end - start) + "毫秒");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bfr.close();
                    bfw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    现在,本人来展示下生成的文件和源文件:
    在这里插入图片描述
    那么,本人在来展示下运行时间:
    在这里插入图片描述
    第一次文件复制所用的时间是87670ms
    第二次文件复制所用的时间是28ms
    本次文件复制所用的时间是49ms

    可以看到,对于大文件而言,我们利用缓冲区的思想来读和写比一个字节一个字节地读写的效率更高
    而本次和第二次的远离大致相同,至于为什么比第二次慢,是因为第二次所设置的缓冲区比默认值大,我们可以在new高效字节输入输出流的对象的时候,自己去设置缓冲区大小。

    (本人《详解 字节流》博文链接:https:////www.cnblogs.com/codderYouzg/p/12418463.html
    (本人 I/O流总集篇 博文链接:https:////www.cnblogs.com/codderYouzg/p/12418404.html

  • 相关阅读:
    MySQL3:索引
    MySQL4:存储过程和函数
    MySQL2:四种MySQL存储引擎
    MySQL1:MySQL函数汇总
    web.xml详解
    SharePoint 多行文本字段设置默认值
    SharePoint Online 自定义Modern UI表单
    Server-side activities have been updated. You need to restart SharePoint Designer to use the updated version of activities.
    计算请假天数JavaScript方法
    SharePoint 2019 离线安装准备工具
  • 原文地址:https://www.cnblogs.com/codderYouzg/p/12418503.html
Copyright © 2011-2022 走看看