java file複製文件效率

複製文件的大小爲2.5G,對比一下使用FileOutputStream和BufferedOutputStream的效率windows

我理解,使用文件流對文件進行讀寫和複製,和在windows上使用鼠標點擊文件複製本質上應該是同樣的code

使用正常的FileOutputStream複製文件:ip

private static void transfer() {
    long t1 = System.currentTimeMillis();
    File file = new File("d:\\CPMS.zip");
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(file);
        fos = new FileOutputStream(new File("D:\\downloads\\" + file.getName()));
        int length = 0;
        byte[] b = new byte[1024];
        while ((length = fis.read(b)) != -1) {
            fos.write(b, 0, length);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    long t2 = System.currentTimeMillis();
    System.out.println("複製文件用時:" + (t2 - t1) + " ms");
}

控制檯輸出get

複製文件用時:22115 ms

使用BufferedOutputStream複製文件:it

private static void copyFile() {
    long t1 = System.currentTimeMillis();
    File file = new File("D:\\CPMS.zip");
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(new File("D:\\downloads\\" + file.getName()));
        bos = new BufferedOutputStream(fos);
        int length = 0;
        byte[] b = new byte[1024];
        while ((length = fis.read(b)) != -1) {
            bos.write(b, 0, length);
        }
        bos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    long t2 = System.currentTimeMillis();
    System.out.println("複製文件用時:" + (t2 - t1) + " ms");
}

控制檯輸出io

複製文件用時:11974 ms

看上去時間差異挺大的,因此建議仍是使用緩衝流來讀寫文件,提升效率效率

相關文章
相關標籤/搜索