NIO FileChannel 零拷贝复制文件

跟風遠走 提交于 2020-05-06 23:10:49

使用 linux 上使用 strace 命令获得系统调用

下面这个会先拷贝到用户空间

public void test2() throws IOException { // 220
    long start = System.currentTimeMillis();
    try (
        FileInputStream inputStream = new FileInputStream("rop.mp4");
        FileChannel inChannel = inputStream.getChannel();
        FileOutputStream outputStream = new FileOutputStream("rop2.mp4");
        FileChannel outChannel = outputStream.getChannel();
    ) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        while (inChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.clear();
        }
    }
    System.out.println(System.currentTimeMillis() - start);
}

下面这个是零拷贝

public void test5() throws IOException { // 29
    long start = System.currentTimeMillis();
    try (
        FileChannel inChannel = FileChannel.open(Paths.get("rop.mp4"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("rop2.mp4"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE)
    ) {
        //inChannel.transferTo(0, inChannel.size(), outChannel);
        outChannel.transferFrom(inChannel, 0, inChannel.size());
    }

    System.out.println(System.currentTimeMillis() - start);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!