I have a folder where I keep log files and I have a job scheduled to run each day to delete old logs.
What's a good way to delete old log files?
Currently, I loop through the directory to read files
File[] listOfFiles = srcFolder.listFiles(fileNameFilter); // this makes an array of files which match a filter I created
for(int i=listOfFiles.length-1; i>0; i--){ // leave at least one file
// listOfFiles[i].lastModified() - in last ten days?
if( what condition ?){
try {
listOfFiles[i].delete();
} catch(Exception e){
}
}
}
I'm thinking
if(listOfFiles[i].lastModified() < tenDaysAgoMS) // where tenDaysAgoMS is the milliseconds ten days ago, but how to implement?
First, you have to subtract the last-modified property to the current time.
See Calendar.getTimeInMillis()
and File.lastModified()
.
Then, you can convert days to milliseconds by multiplying them to 1000 * 60 * 60 * 24
.
1000ms
= 1s
60s
= 1m
60m
= 1h
24h
= 1d
long now = Calendar.getInstance().getTimeInMillis();
long oneDay = 1000L * 60L * 60L * 24L;
long tenDays = 10L * oneDay;
File log = listOfFiles[i];
long diff = now - log.lastModified();
if (diff > tenDays) {
log.delete();
}