将指定目录下的文件、子目录及子目录文件复制一份到另一指定目录

package org.icss.xmfj;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;


/**
 * 从指定目录下复制所有文件及目录到另一指定目录下
 *
 *
 */
public class RemoveFileTest {



    public static void copyFilesFromDirToDir(String sourceDirPath, String destinationDirPath) throws IOException {
        File sourceDir = new File(sourceDirPath);
        File destinationDir = new File(destinationDirPath);

        if (!sourceDir.exists()) {
            throw new IOException("Source directory does not exist: " + sourceDirPath);
        }

        if (!destinationDir.exists()) {
            destinationDir.mkdirs(); // 创建目标目录(如果不存在)
        }

        for (File file : sourceDir.listFiles()) {
            if (file.isDirectory()) {
                // 递归处理子目录
                String newDestinationDirPath = destinationDirPath + File.separator + file.getName();
                copyFilesFromDirToDir(file.getAbsolutePath(), newDestinationDirPath);
            } else {
                // 复制文件
                copyFile(file, new File(destinationDir, file.getName()));
            }
        }
    }

    private static void copyFile(File sourceFile, File destFile) throws IOException {
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }

        // 使用Java NIO的Files类进行文件复制(更简洁且支持大文件)
        Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

        // 或者使用传统的IO方式(对于小文件或需要更细粒度控制的情况)
        // try (FileInputStream fis = new FileInputStream(sourceFile);
        //      FileOutputStream fos = new FileOutputStream(destFile)) {
        //     byte[] buffer = new byte[1024];
        //     int length;
        //     while ((length = fis.read(buffer)) > 0) {
        //         fos.write(buffer, 0, length);
        //     }
        // }
    }

    public static void main(String[] args) {
        String sourceDirPath = "D:\\111\\sourceFiles\\20240520";
        String destinationDirPath = "D:\\111\\targetFiles";

        try {
            copyFilesFromDirToDir(sourceDirPath, destinationDirPath);
            System.out.println("Files copied successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值