20

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?

Ralph
  • 3,939
  • 6
  • 41
  • 71
  • Does http://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified contain the answer to your question? – sverre Jun 12 '11 at 07:05
  • Have you tried FileUtils.dirListByAscendingDate? http://www.rgagnon.com/javadetails/java-0606.html – excanoe Jun 12 '11 at 07:05
  • 1
    You seem to be interested in log files. These are often named in a way such that lexical sorting by file name also sorts by time. – Ted Hopp Jun 12 '11 at 07:05

3 Answers3

39

Java 8

public static void sortOldestFilesFirst(File[] files) {
    Arrays.sort(files, Comparator.comparingLong(File::lastModified));
}

public static void sortNewestFilesFirst(File[] files) {
    Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
}

Java 7

public static void sortOldestFilesFirst(File[] files) {
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File a, File b) {
            return Long.compare(a.lastModified(), b.lastModified());
        }
    });
}

public static void sortNewestFilesFirst(File[] files) {
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File a, File b) {
            return Long.compare(b.lastModified(), a.lastModified());
        }
    });
}
fredoverflow
  • 246,999
  • 92
  • 370
  • 646
javing
  • 11,899
  • 31
  • 135
  • 206
3

Your best option is to use a comparator. There is a similar question and answer here... Best way to list files in Java, sorted by Date Modified?

Community
  • 1
  • 1
Ben
  • 1,525
  • 10
  • 19
0

I would use FileUtils in commons-io to get back the Collection of Files. I would then apply a custom comparator. It should be pretty easy.

javamonkey79
  • 17,217
  • 36
  • 108
  • 170