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(); } } }
将指定目录下的文件、子目录及子目录文件复制一份到另一指定目录
最新推荐文章于 2024-07-14 22:26:46 发布