Java删除目录可以使用java.nio.file 包中 Files 类。Files 类提了delete 和 deleteIfExists方法来删除文件或目录,以及walkFileTree方法结合SimpleFileVisitor递归地处理目录树。
使用java.nio.file 递归删除目录:
import java.nio.file.*;
import java.io.IOException;
public class DeleteDirectoryExample {
public static void main(String[] args) {
// 定义目录路径
Path directoryPath = Paths.get("path/to/directory");
try {
// 递归删除目录及其内容
deleteRecursively(directoryPath);
// 输出成功信息
System.out.println("目录删除成功: " + directoryPath);
} catch (IOException e) {
// 处理异常
System.err.println("删除目录时出错: " + e.getMessage());
}
}
/**
* 递归地删除目录及文件
*
* @param dir 要删除的目录
* @throws IOException 如果删除过程中发生 I/O 错误
*/
public static void deleteRecursively(Path dir) throws IOException {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// 删除文件
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
// 删除空目录
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// 如果删除文件失败
throw exc;
}
});
}
}
使用 java.io.File进行删除:
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
// 删除test目录
deleteDir(new File("./test"));
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir
(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
if(dir.delete()) {
System.out.println("目录已被删除!");
return true;
} else {
System.out.println("目录删除失败!");
return false;
}
}
}
1033

被折叠的 条评论
为什么被折叠?



