java 实现高效复制文件,提高性能,NIO和IO复制大文件的时间测试,实战。

java nio/io复制文件 工具类实现。

package com.tencentyun.util;

import org.junit.Test;

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

public class NioFileUtils {


    public void nioCopyTo(String filePath, String destFilePath) {
        long startTime = System.currentTimeMillis();   //获取开始时间

        try (FileInputStream fileInputStream = new FileInputStream(new File(filePath));
             FileOutputStream fileOutputStream = new FileOutputStream(new File(destFilePath));
             FileChannel in = fileInputStream.getChannel();//得到对应的文件通道
             FileChannel out = fileOutputStream.getChannel();//得到对应的文件通道
        )
        {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024);//缓冲区大小
            while ((in.read(byteBuffer)) != -1) {
                //切换读取模式
                byteBuffer.flip();
                out.write(byteBuffer);
                byteBuffer.clear();
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("nio 复制文件 程序运行时间: " + (endTime - startTime) + "ms");
    }

    public void copyTo(String filePath, String destFilePath) {
        long startTime = System.currentTimeMillis();   //获取开始时间
        try (
                InputStream fileInputStream = new FileInputStream(new File(filePath));
                OutputStream fileOutputStream = new FileOutputStream(new File(destFilePath));
        ) {
            int len = 0;
            byte[] bytes = new byte[1024 * 1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("io 复制文件 程序运行时间: " + (endTime - startTime) + "ms");
    }


    @Test
    public void testCopyFile() {
        nioCopyTo("D:\\Download\\ideaIU-2018.3.6.exe", "D:\\temp\\ideaIU-NIO.exe");
        copyTo("D:\\Download\\ideaIU-2018.3.6.exe", "D:\\temp\\ideaIU-IO.exe");

    }
}

文 件:600M
复制时间:NIO 耗时:327ms ,IO耗时:667ms
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值