How to sort files from a directory by date in java?

Viewed 41505

I have a method which reads the content from files located in a directory. But for functional reasons it is necessary to start with the oldest file (indicated by the property lastmodified) and end with the newest file.

This is the code how I open and read the files:

        FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.matches("access_log.*");
        }
    };

    File folder = new File("/home/myfiles");
    File[] listOfFiles = folder.listFiles(filter);

    for (int i = 0; i < listOfFiles.length; i++) {
        String sFileName = listOfFiles[i].getName();
        File accessLogFile = new File(aLog.getPath(), sFileName);
        long time=accessLogFile.lastModified();
        // do something with the file
    }

Has anybody a solution how I can quickly sort my list of files by date?

3 Answers
Related