Java递归删除目录和复制子目录案例
package com.et;
import java.io.File;
import java.io.IOException;
/*
* 首先检查源位置是否是目录,
* 如果是,则创建目标位置的目录(如果它尚不存在),
* 然后递归复制每个子项。
* 如果源位置是文件,则简单地使用java.nio.file.Files.copy方法复制文件
*
* */
public class DirectoryCopier {
/**
* 复制目录
* @param sourceDir 原目录
* @param targetDir 目标目录
* @throws IOException
*/
public static void copyDirectory(File sourceDir, File targetDir) throws IOException {
if(targetDir.exists()){
System.out.println("目标目录已存在");
deleteFolder(targetDir);
}
if (sourceDir.isDirectory()) {
if (!targetDir.exists()) {
targetDir.mkdir();
System.out.println("目录创建成功:" + targetDir);
}
String[] children = sourceDir.list();
for (String child : children) {
copyDirectory(new File(sourceDir, child), new File(targetDir, child));
}
} else {
java.nio.file.Files.copy(sourceDir.toPath(), targetDir.toPath());
System.out.println("文件复制成功:" + sourceDir + " 到 " + targetDir);
}
}
public static void main(String[] args) {
try {
File source = new File("D:/static");
File dest = new File("D:/static2");
copyDirectory(source, dest);
//deleteFolder(new File("D:/static2"));
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 删除目录及子目录下的所有文件
* */
public static void deleteFolder(File folder) {
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
deleteFolder(file);
}
}
}
folder.delete();
System.out.println("目录:"+folder.getName()+" 删除完成");
}
}