java.nio transferTo似乎不可能快?

hav*_*ked 4 java nio

有人可以解释一下该transferTo方法如何以看似1000+ MB /秒的速度复制文件.我使用372MB二进制文件运行了一些测试并且第一个副本很慢,但如果我更改输出名称并再次运行它,输出目录中会出现一个额外的文件,只需180ms,超过2000 MB /秒.这里发生了什么?我正在运行Windows 7.

private static void doCopyNIO(String inFile, String outFile) {
    FileInputStream     fis = null;
    FileOutputStream    fos = null;
    FileChannel         cis = null;
    FileChannel         cos = null;

    long                len = 0, pos = 0;

    try {
        fis = new FileInputStream(inFile);
        cis = fis.getChannel();
        fos = new FileOutputStream(outFile);
        cos = fos.getChannel();
        len = cis.size();
        while (pos < len) {
            pos += cis.transferTo(pos, (1024 * 1024 * 10), cos);    // 10M
        }
        fos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cos != null) { try { cos.close(); } catch (Exception e) { } }
        if (fos != null) { try { fos.close(); } catch (Exception e) { } }
        if (cis != null) { try { cis.close(); } catch (Exception e) { } }
        if (fis != null) { try { fis.close(); } catch (Exception e) { } }
    }
}
Run Code Online (Sandbox Code Playgroud)

chr*_*ke- 6

关键是"第一次".您的操作系统已将整个文件缓存在RAM中(目前372MB并不多),因此唯一的开销是将零复制缓冲区翻转到内存映射空间所需的时间.如果您刷新缓存(不知道如何在Windows上执行此操作;如果文件位于外部驱动器上,您可以拔下并重新插入),您将看到安定下来读取速率,并且如果您强制操作系统刷新写入,如果你有硬盘,程序将阻塞10秒左右.