java删除当前文件以及包括当前所在文件夹及其所有子文件夹的所有空文件夹
@Test
public void testDeleteFileAndEmptyDirectory() {
deleteFileAndEmptyDirectory("D:\\Temp\\testFile\\", "111.txt");
}
public static void deleteFile(String filePath) {
File file = new File(filePath);
System.out.println(filePath);
System.out.println("file.exists() is " + file.exists());
if (file.delete()) {
System.out.println("文件删除成功!");
} else {
System.out.println("删除失败");
}
}
public static void deleteEmptyDirectory(File file) {
if (file == null) return;
if (!file.exists()) {
System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
return;
}
File[] files = file.listFiles();
if (files == null || files.length == 0) {
System.out.print("目录名:" + file.getName());
file.delete();
System.out.println("被删除!");
return;
}
for (File f : files) {
if (f.isDirectory()) deleteEmptyDirectory(f);
}
if (file != null && file.listFiles().length == 0) {
System.out.print("目录名:" + file.getName());
file.delete();
System.out.println("被删除!");
}
}
public static void deleteFileAndEmptyDirectory(String directoryPath, String fileName) {
deleteFile(directoryPath + "\\" + fileName);
deleteEmptyDirectory(new File(directoryPath));
}