高性能文件拷贝

java 复制代码
package cn.itcast.nio.c3;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class TestFileChannelTransferTo {
    public static void main(String[] args) {
        try (
                FileChannel from = new FileInputStream("data.txt").getChannel();
                FileChannel to = new FileOutputStream("to.txt").getChannel();
        ) {
            from.transferTo(0, from.size(), to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

NIO文件流拷贝文件

使用零拷贝

这样写法有问题 transferTo 方法最多只能传输2G的文件

进行优化代码

java 复制代码
package cn.itcast.nio.c3;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class TestFileChannelTransferTo {
    public static void main(String[] args) {
        try (
                FileChannel from = new FileInputStream("data.txt").getChannel();
                FileChannel to = new FileOutputStream("to.txt").getChannel();
        ) {
            // 效率高,底层会利用操作系统的零拷贝进行优化, 2g 数据
            long size = from.size();
            // left 变量代表还剩余多少字节
            for (long left = size; left > 0; ) {
                System.out.println("position:" + (size - left) + " left:" + left);
                left -= from.transferTo((size - left), left, to);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
光而不耀@lgy12 分钟前
C++初登门槛
linux·开发语言·网络·c++·后端
lkbhua莱克瓦2416 分钟前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
Mr__Miss20 分钟前
面试踩过的坑
java·开发语言
啊丢_22 分钟前
C++——Lambda表达式
开发语言·c++
Chh07151 小时前
《R语言SCI期刊论文绘图专题计划》大纲
开发语言·r语言
Yeats_Liao1 小时前
Go 语言 TCP 端口扫描器实现与 Goroutine 池原理
开发语言·tcp/ip·golang
Thomas_YXQ2 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
liuweidong08022 小时前
【Pandas】pandas DataFrame rsub
开发语言·python·pandas
whoarethenext2 小时前
c++的jsoncpp使用
开发语言·c++·jsoncpp
niuTaylor3 小时前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#