FileChanel复制文件比传统方法慢?

试了下用FileChanel.transferTo复制一个4G多的文件,和用传统IO复制,发现FileChannel居然并没有更快。这是为什么呢?代码如下:

package com.example.demo.nio;

import org.springframework.util.StopWatch;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;

public class FileChannelTest {
    public static void main(String[] args) {
        String fromPath = "D:\\softpackages\\CentOS-7-x86_64-DVD-2009.iso";
        String toPath = "D:\\softpackages\\CentOS-7-x86_64-DVD-2009_back.iso";
//        String fromPath = "D:\\softpackages\\mysql-8.0.27-winx64.zip";
//        String toPath = "D:\\softpackages\\mysql-8.0.27-winx64_back.zip";
        Path from = Paths.get(fromPath);
        Path to = Paths.get(toPath);

        StopWatch stopWatch = new StopWatch();

        stopWatch.start("传统方法复制文件");
        traditional(from, to);
        stopWatch.stop();

        stopWatch.start("nio复制文件");
        fileChannel(from, to);
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
    }

    private static void fileChannel(Path from, Path to) {
        try(FileChannel channel = FileChannel.open(from, StandardOpenOption.READ);
            FileChannel toChannel = FileChannel.open(to, StandardOpenOption.WRITE)){
            long size = channel.size();
            long left = size;
            while(left>0){
                left-=channel.transferTo(size-left,left,toChannel);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void traditional(Path from, Path to) {
        try(BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(from));
            BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(to))){
            byte[] buffer = new byte[1024*1024*200];
            int read = inputStream.read(buffer);
            while(read!=-1){
                outputStream.write(buffer,0,read);
                read = inputStream.read(buffer);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

运行结果显示FileChannel并没有更快。调换顺序,影响不大。

换200+M的文件试了下,fileChannel有明显优势

不懂为什么大文件(G级),用FIleChannel并没有优势,有大佬能解释吗?

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值