1 需求
需求1:删除目录,不管是否非空;
需求2:删除空目录;
需求3:删除非空目录;
2 接口
- File
- delete()
- deleteOnExit()
- Files
- delete()
- deleteIfExists()
3.X 示例:删除空目录
import java.io.File;public class Main {public static void main(String[] args) {try {// 创建一个新的File对象File dir = new File("path/to/directory");// 如果目录存在,则删除它if (dir.exists()) {boolean result = dir.delete();if (result) {System.out.println("Directory deleted successfully!");} else {System.out.println("Failed to delete directory.");}} else {System.out.println("Directory does not exist.");}} catch (Exception e) {e.printStackTrace();}}
}
3.X 示例:删除非空目录
import java.io.File;public class DirectoryDeleter {public static void main(String[] args) {File directory = new File("path/to/directory");deleteDirectory(directory);}public static void deleteDirectory(File directory) {if (directory.exists()) {File[] files = directory.listFiles();if (files != null) {for (File file : files) {if (file.isDirectory()) {deleteDirectory(file); // 递归删除子目录} else {file.delete(); // 删除文件}}}directory.delete(); // 删除目录}}
}