Buffered In/Out Stream的正确食用方法

问题引出

众所周知,Buffered In/OutputStream 因为有缓冲区,所以减少了与硬盘的交互次数,提高了效率,但是在测试复制文件的速度时,欠着的速度却远慢于后者
代码:

public class Test {

    public static void main(String[] args) throws IOException {
        long start=System.currentTimeMillis();
        copy1();
        long end=System.currentTimeMillis();
        sop((end-start)+"毫秒");
        start=System.currentTimeMillis();
        copy2();
        end=System.currentTimeMillis();
        sop((end-start)+"毫秒");
    }
    public static void copy1() throws IOException{
        BufferedInputStream buf = new BufferedInputStream(new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4"));
        BufferedOutputStream bufo=new BufferedOutputStream(new FileOutputStream("F:\\TCPServer.mp4"));
        int ch;
        while((ch=buf.read())!=-1){
            bufo.write(ch);
        }
        buf.close();
        bufo.close();
    }
    public static void copy2() throws IOException{
        FileInputStream fin=new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4");
        FileOutputStream fout=new FileOutputStream("F:\\TCPServer2.mp4");
        byte [] buf=new byte[1024];
        int len;
        while((len=fin.read(buf))!=-1){
            fout.write(buf,0,len);
        }
        fin.close();
        fout.close();
    }
}

多次实验后发现copy1的运行时间在30 s左右,但copy2仅需70 ms(MP4的大小14.7M)

原因

Buffered In/OutputStream虽然内部有缓冲区,但是在外部仍然需要定义一个byte数组

public class Test {

    public static void main(String[] args) throws IOException {
        long start=System.currentTimeMillis();
        copy1();
        long end=System.currentTimeMillis();
        sop((end-start)+"毫秒");
        start=System.currentTimeMillis();
        copy2();
        end=System.currentTimeMillis();
        sop((end-start)+"毫秒");
    }
    public static void copy1() throws IOException{
        BufferedInputStream buf = new BufferedInputStream(new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4"));
        BufferedOutputStream bufo=new BufferedOutputStream(new FileOutputStream("F:\\TCPServer.mp4"));
        byte [] bufb=new byte [1024];
        int len;
        while((len=buf.read(bufb))!=-1){
            bufo.write(bufb,0,len);
        }
        buf.close();
        bufo.close();
    }
    public static void copy2() throws IOException{
        FileInputStream fin=new FileInputStream("E:\\DELL\\Pictures\\视频项目\\作业one.mp4");
        FileOutputStream fout=new FileOutputStream("F:\\TCPServer2.mp4");
        byte [] buf=new byte[1024];
        int len;
        while((len=fin.read(buf))!=-1){
            fout.write(buf,0,len);
        }
        fin.close();
        fout.close();
    }
}

现在复制时copy1的速度为20 msms左右,copy2在70 ms左右,带缓冲区效率确实高

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容