0

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.
AgentM
  • 406
  • 4
  • 18
  • The only work around I could think of is using #0001 and #0010, aka leading zeroes... which is ok I guess, but I rather have it without. – AgentM Oct 19 '16 at 20:18
  • You could sort based on file name, then convert your manieth number to an int and sort each date section based on that. – Jacob H Oct 19 '16 at 20:20
  • As an alternative, you can sort files [by date, literally](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#lastModified()) – default locale Oct 19 '16 at 20:25
  • I now just figured, deleting #0 and re-running the application, will generate file #0 again because it doesn't exist anymore. The way I implemented it. so I think I should change this to sorting on date modified. – AgentM Oct 19 '16 at 20:26
  • thanks anyway somebody can close this post as duplicate, well after I edited it because my requirements changed :/ blargh, hate it when your brain pulls you through a mangle bath like this. – AgentM Oct 19 '16 at 20:40

0 Answers0