高性能文件拷贝

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();
        }
    }
}
相关推荐
mit6.8246 分钟前
[Nagios Core] struct监控对象 | 配置.cfg加载为内存模型
c语言·开发语言
序属秋秋秋23 分钟前
《C++初阶之STL》【泛型编程 + STL简介】
开发语言·c++·笔记·学习
NCHUtianlin25 分钟前
JAVA生成PDF(itextpdf)
java·开发语言·pdf
Sylvia-girl6 小时前
Java——抽象类
java·开发语言
Yana.nice8 小时前
Bash函数详解
开发语言·chrome·bash
tomorrow.hello10 小时前
Java并发测试工具
java·开发语言·测试工具
晓131310 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊10 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
她说人狗殊途11 小时前
java.net.InetAddress
java·开发语言
天使day11 小时前
Cursor的使用
java·开发语言·ai