Java NIO 本地零拷贝transferFrom、transferTo与Buffer拷贝

原理流程图

在这里插入图片描述

从Buffer中拷贝

    public static void main(String[] args) throws Exception {
        //=========== 读 ===========
        //拿到文件
        File file = new File("d:\\test\\write.txt");
        FileInputStream inputStream = new FileInputStream(file);
        //创建管道,把文件放入通道
        FileChannel fileChannel = inputStream.getChannel();
        //创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
        //从通道读数据放入缓冲区
        fileChannel.read(buffer);

        //=========== 反转读写模式 ===========
        buffer.flip();

        //=========== 写 ===========
        //创建文件
        FileOutputStream outputStream = new FileOutputStream("d:\\test\\write2.txt");
        //创建Channel2,把文件放入通道
        FileChannel fileChannel2 = outputStream.getChannel();
        //把Buffer内容放入Channel2
        fileChannel2.write(buffer);

        //=========== 关闭与清除 ===========
        fileChannel2.close();
        outputStream.close();
        fileChannel.close();
        inputStream.close();
        buffer.clear();
    }

调用transferFrom或transferTo,直接复制通道数据

public static void main(String[] args) throws Exception {
    //=========== 创建读通道 ===========
    //拿到文件
    File file = new File("d:\\test\\write.txt");
    FileInputStream inputStream = new FileInputStream(file);
    //创建管道,把文件放入通道
    FileChannel fileChannel = inputStream.getChannel();


    //=========== 创建写通道 ===========
    //创建文件
    FileOutputStream outputStream = new FileOutputStream("d:\\test\\write22.txt");
    //创建Channel2,把文件放入通道
    FileChannel fileChannel2 = outputStream.getChannel();

    //=========== transferFrom从目标通道复制到当前通道 ===========
    fileChannel2.transferFrom(fileChannel,0,fileChannel.size());

    //=========== 关闭与清除 ===========
    fileChannel2.close();
    outputStream.close();
    fileChannel.close();
    inputStream.close();
}

你可能感兴趣的:(IO,Java,java)