一、删除文件夹及其子文件
public class DelFilesOrFolders {
public static void main(String args[]) {
String folderPath = "/Users/mac/Desktop/var/";
delFolder(folderPath);
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
File myFilePath = new File(folderPath);
myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void delAllFile(String folderPath) {
File file = new File(folderPath);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (folderPath.endsWith(File.separator)) {
temp = new File(folderPath + tempList[i]);
} else {
temp = new File(folderPath + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
} else if (temp.isDirectory()) {
delAllFile(folderPath + "/" + tempList[i]);
delFolder(folderPath + "/" + tempList[i]);
}
}
}
}
二、删除特定文件
public class DelSpecificFile {
public static void main(String args[]) {
LocalDate now = LocalDate.now();
LocalDate tenDaysAgo = now.plusDays(-10);
String dateStr = tenDaysAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
deleteFilesForPathByPrefix(Paths.get("/Users/mac/Desktop/var/"), "del." + dateStr);
}
public static void deleteFilesForPathByPrefix(final Path path, final String prefix) {
try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path, prefix + "*")) {
for (final Path newDirectoryStreamItem : newDirectoryStream) {
Files.delete(newDirectoryStreamItem);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}