/**标签:递归,getName,30,System,replace,println,日志,dir,out From: https://blog.51cto.com/u_11288266/5871444
* 递归删除大于30天的旧日志
*/
private static void deleteOldLogFiles(File dir) {
if (dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
deleteOldLogFiles(file);
}
}
}
// System.out.println(dir.getName());
// System.out.println(dir.getName().endsWith(".log"));
String replace = dir.getName().replace(".log", "");
System.out.println(replace);
// System.out.println(compare(replace));
if (dir.getName().endsWith(".log") && compare(replace)) {
boolean delete = dir.delete();
System.out.println("delete = " + delete);
}
}
/**
* @return 相差大于30天
*/
private static boolean compare(String oldFileName) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
//跨年不会出现问题
//如果时间为:2016-03-18 11:59:59 和 2016-03-19 00:00:01的话差值为 0
String curDate = sdf.format(new Date());
// Date newDate = sdf.parse("2022-12-25");
long days = 0;
days = (new Date().getTime() - sdf.parse(oldFileName).getTime()) / (1000 * 3600 * 24);
// System.out.print(days);
return days > 30;
} catch (ParseException e) {
return false;
}
}