【Java】复制 源文件/文件夹 至目标文件夹

【Java】复制 源文件/文件夹 至目标文件夹

  1. 对于源文件,直接使用Java NIO中提供的FileChannel进行复制,要注意的是在目标文件夹中需要先创建不存在的文件夹才能复制文件
private static void copyFile(File fromFile, File toFile) throws IOException {
        if (!toFile.exists()) toFile.getParentFile().mkdirs();
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(fromFile).getChannel();
            outputChannel = new FileOutputStream(toFile).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            Objects.requireNonNull(inputChannel).close();
            Objects.requireNonNull(outputChannel).close();
        }
    }
  1. 对于源文件夹,通过递归进行遍历,调用copyFile方法进行文件复制。
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
     * 复制文件或文件夹
     * @param from 文件 / 文件夹
     * @param toDir 目标文件夹
     */
    public void copyToDir(File from, File toDir) {
        if (from == null || toDir == null) {
            logger.error("源路径或目标路径为空,无法完成复制,请检查传入参数。");
            return;
        }
        if (!from.exists()) {
            logger.error("源路径不存在,无法完成复制。");
            return;
        }
        if (!toDir.isDirectory()) {
            logger.error("目标路径不是文件夹类型,无法完成复制。");
            return;
        }
        if (!toDir.exists()) {
            boolean mkdirs = toDir.mkdirs();
        }

        if (from.isFile()) {
            try {
                copyFile(from, new File(toDir.getAbsolutePath() + File.separator + from.getName()));
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("复制文件错误 --->>> " + from.getAbsolutePath() + e);
            }
        } else if (from.isDirectory()) {
            File newToDir = new File(toDir.getAbsolutePath() + File.separator + from.getName());
            newToDir.mkdirs();
            File[] froms = from.listFiles();
            if (froms == null) return;
            for (File file : froms) {
                copyToDir(file, newToDir);
            }
        } else {
            logger.error("复制文件失败 --->>> 原因未知");
        }
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值