EDIT NOTE: See below, I require files to be sorted on modified date instead.
I have been breaking my mind on this one for quite some time:
I have an array of strings of pathnames, log files. I want to delete the oldest ones when a certain amount/size for the log files is reached.
The format for the filenames is: the date, the how manieth log of that date + .log
e.g. "2016-10-19-#1.log", "2016-10-19-#2.log", "2016-10-19-#3.log"
when I sort using Collections.sort(arrayList);
the entries "2016-10-19-#1.log", "2016-10-19-#2.log" and "2016-10-19-#10.log"
will be sorted into #1, #10 and #2. instead of #1, #2 and #10
What I am aiming for is to ultimately have the oldest log files be deleted.
Here a code snippet:
File directory = new File(pathToDir);
FilenameFilter fnf = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".log");
}
};
int dirCount = directory.listFiles(fnf).length;
if (dirCount > maxLogCache) {
for(File file2 : directory.listFiles(fnf)) {
file2.delete();
dirCount--;
if (dirCount <= maxLogCache) {
break;
}
}
}
This will delete files in order #1, #10, #11, #2, #3 ... if files #1 through #11 exist.
NEW EDIT sorry for the style
Instead of using the string of the filename to sort the array(list), it is required to get the lastModified date from the File.
File directory = new File(pathToDir);
FilenameFilter fnf = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".log");
}
};
int dirCount = directory.listFiles(fnf).length;
// Code for sorting based on lastModified.