import java.io.File;
/**
* @description:
* @author: yuanchuan
* @create: 2021/08/06
**/
public class CleanBlankFile {
static File globalFile;
public static void main(String[] args) {
// 你的repository的绝对路径
globalFile = new File("E:\\java_developsoft\\maven\\repository");
if (globalFile == null && !globalFile.exists()) {
System.out.println("你所输入的文件非法,可能不存在,请更换路径");
}
deleteFailedAndBlankFile(globalFile);
}
private static void deleteFailedAndBlankFile(File globalFile) {
deleteSubFile(globalFile);
}
private static File deleteSubFile(File file) {
if (file == null) {
return null;
}
if (file.exists()) {
if(file.isFile()){
if(file.getName().endsWith("lastUpdated")){
file.delete();
System.out.println("删除文件:" + file.getAbsolutePath());
deleteBlankParentFile(file.getParentFile());
return null;
}
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files.length == 0) {
file.delete();
System.out.println("删除文件:" + file.getAbsolutePath());
File parentFile = file.getParentFile();
deleteBlankParentFile(parentFile);
return null;
}
for (File file1 : files) {
deleteSubFile(file1);
}
}
}
return null;
}
private static File deleteBlankParentFile(File parentFile) {
int length = parentFile.listFiles().length;
if (length == 0 && !parentFile.getName().equals(globalFile.getName())) {
parentFile.delete();
System.out.println("删除文件:" + parentFile.getAbsolutePath());
deleteBlankParentFile(parentFile.getParentFile());
}
return null;
}
}