字节流 与 字节缓冲流-效率PK

字节流与缓冲字节流的区别:

  • 操作方式:字节流字节操作文件,字节缓冲流先将数据添加到缓冲区,再将数据写入到文件中(或者读取文件);
  • 效率:字节缓冲流的效率要高于字节流;

 代码实现-测试效率

实现思路

1.复制一个大小为115M的视频文件

2.记录读取开始时间与结束时间

3.计算复制的时间

 实现方法

1. 基本字节流一次读写一个字节
2. 基本字节流一次读写一个字节数组
3. 字节缓冲流一次读写一个字节
4. 字节缓冲流—次读写一个字节数组

 计算时间方法 

使用System.currentTimeMillis()计算

    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();

        Stream1();
        Stream2();
        BufferedStream1();
        BufferedStream2();

        long end = System.currentTimeMillis();
        System.out.println("花费了:"+(end-start)+"ms");

    }
1. 字节流一次读写一个字节
    //基本字节流一次读写一个字节
    public static void Stream1() throws IOException {
        InputStream in = new FileInputStream("File\\晴天mv.mp4");
        OutputStream out = new FileOutputStream("File\\晴天副本mv.mp4");

        int len;

        while ((len = in.read()) != -1){
            out.write(len);
        }
        in.close();
        out.close();

    }

运行结果

花费分时间约为17分钟

2.字节流一次读写一个字节数组
    //基本字节流一次读写一个字节数组
    public static void Stream2() throws IOException {
        InputStream in = new FileInputStream("File\\晴天mv.mp4");
        OutputStream out = new FileOutputStream("File\\晴天副本mv.mp4");

        byte[] bytes = new byte[1024];
        int len;

        while ((len = in.read(bytes)) != -1){
            out.write(bytes,0,len);
        }
        in.close();
        out.close();
    }

运行结果

花费1.579s

3. 字节缓冲流一次读取一个字节 
    // 字节缓冲流一次读写一个字节
    public static void BufferedStream1() throws IOException {
        InputStream in = new FileInputStream("File\\晴天mv.mp4");
        OutputStream out = new FileOutputStream("File\\晴天副本mv.mp4");
        BufferedInputStream bin = new BufferedInputStream(in);
        BufferedOutputStream bout = new BufferedOutputStream(out);

        int len;

        while ((len = bin.read()) != -1){
            bout.write(len);
        }
        bin.close();
        bout.close();
    }

运行结果

花费2.8844s

 
4. 字节缓冲流一次读取一个字节数组
    // 字节缓冲流一次读写一个字节数组
    public static void BufferedStream2() throws IOException {
        InputStream in = new FileInputStream("File\\晴天mv.mp4");
        OutputStream out = new FileOutputStream("File\\晴天副本mv.mp4");
        BufferedInputStream bin = new BufferedInputStream(in);
        BufferedOutputStream bout = new BufferedOutputStream(out);

        byte[] bytes = new byte[1024];
        int len;

        while ((len = bin.read(bytes)) != -1){
            bout.write(bytes,0,len);
        }
        bin.close();
        bout.close();
    }

运行结果

花费了0.396s

结果分析 

        通过实验我们可以得到在同样读取一个字节或一个字节数组的条件下,字节缓冲流的读写速度明显快于普通字节流。其中一次读取一个字节时,缓冲流快了约357倍,一次读取一个字节数组时缓冲流快了约4倍。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值