public static void main(String[] args) {
File dir = new File("c:/test");
String matchName = "test.*\\.txt";
int keepDays = 5;
boolean recursive = true;
removeOldFile(dir, recursive, matchName, keepDays);
}
private static void removeOldFile(File dir, boolean recursive, String matchName,
int keepDays) {
DecimalFormat df = new DecimalFormat("0.00");
String[] extensions = null;
Collection files = FileUtils.listFiles(dir, extensions, recursive);
long currentTime = System.currentTimeMillis();
for (File f : files) {
String oneFileName = f.getName();
//System.out.println(oneFileName + ":" + oneFileName.matches(matchName));
if(oneFileName.matches(matchName)) {
long fileLastModified = f.lastModified();
long timeGap = currentTime - fileLastModified;
System.out.println("timeGap for file:" + f.getAbsolutePath() + " is " + df.format(timeGap / 1000.0 / 24 / 3600) + " day");
if(timeGap > keepDays * 24L * 3600 * 1000) {
System.out.println("begin to delete file:" + f.getAbsolutePath());
if(!f.delete()) {
throw new RuntimeException("delete file failed:" + f.getAbsolutePath());
}
}
}
}
}