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

問題引出

眾所周知,Buffered In/OutputStream 因為有緩沖區(qū),所以減少了與硬盤的交互次數(shù),提高了效率,但是在測試復制文件的速度時,欠著的速度卻遠慢于后者
代碼:

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\\視頻項目\\作業(yè)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\\視頻項目\\作業(yè)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();
    }
}

多次實驗后發(fā)現(xiàn)copy1的運行時間在30 s左右,但copy2僅需70 ms(MP4的大小14.7M)

原因

Buffered In/OutputStream雖然內(nèi)部有緩沖區(qū),但是在外部仍然需要定義一個byte數(shù)組

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\\視頻項目\\作業(yè)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\\視頻項目\\作業(yè)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();
    }
}

現(xiàn)在復制時copy1的速度為20 msms左右,copy2在70 ms左右,帶緩沖區(qū)效率確實高

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容