Java

发布时间 2023-08-24 15:41:09作者: 行走的思想

https://blog.csdn.net/Eric_splendid/article/details/79898536

 

测试:1.06GB 视频文件,耗时17秒

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

//原文链接:https://blog.csdn.net/Eric_splendid/article/details/79898536

public class CopyFileUtil {

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        boolean b = false;
        try {
            b = copyFile("D:\\test\\123.mp4", "D:\\test1\\123.mp4");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(b + "------------------");
        System.out.println(System.currentTimeMillis() - l);
    }

    // 复制文件
    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;
        }
    }
}