java大文件复制最高效方法:FileChannel(已测)

话不多说,上代码:

 

package com.yhfund.file.util;


import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 *
 * @author yq.wang
 * @Date 2018/4/10
 * @Time 16:36
 * Description: 复制文件
 */
public class CopyFileUtil {
    // 复制文件
    public static boolean copyFile(String source, String target) throws Exception {


        source = source.replace("\\", "/");
        target = target.replace("\\", "/");


        File source_file = new File(source);
        File target_file = new File(target);


        FileChannel in = null;
        FileChannel out = null;
        if (!source_file.exists() || !source_file.isFile()) {
            throw new IllegalArgumentException(source_file + "文件不存在!");
        }
        File parent = target_file.getParentFile();
        // 创建目标文件路径文件夹
        if (!parent.exists()) {
            parent.mkdirs();
        }
        // 判断目标文件是否存在
        if (target_file.exists()) {
            target_file.delete();
        }
        // 创建目标文件
        if (!target_file.exists()) {
            target_file.createNewFile();
        }


        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(source_file);
            outStream = new FileOutputStream(target_file);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inStream.close();
            in.close();
            outStream.close();
            out.close();
        }
        if (!target_file.exists()) {
            return false;
        } else if (source_file.length() != target_file.length()) {
            return false;
        } else {
            return true;
        }
    }
}

测试类:

 

package com.yhfund.file.util;


import org.junit.Test;


import java.io.File;
import java.io.IOException;


import static org.junit.Assert.*;


/**
 * Created by wensi on 2018/4/10.
 */
public class CopyFileUtilTest {


    private CopyFileUtil copyFileUtil;


    @Test
    public void copyFile() throws Exception {
        long l = System.currentTimeMillis();
        boolean b = copyFileUtil.copyFile("D:\\test\\OFD_5C_150_20170918_02_100W.TXT", "D:\\test1\\OFD_5C_150_20170918_02_100W.TXT");
        System.out.println(b+"------------------");
        System.out.println(System.currentTimeMillis()-l);
    }


}
 

我用的测试类是junit测试,大家也可以用普通的测试类main方法进行测试,别忘了在CopyFileUtil方法前加上static

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值