How do I sort files based on their last modified date?

This example demonstrates how to use Apache Commons IO LastModifiedFileComparator class to sort files based on their last modified date in ascending and descending order. There are two comparators defined in this class, the LASTMODIFIED_COMPARATOR and the LASTMODIFIED_REVERSE.

package org.kodejava.example.commons.io;

import static org.apache.commons.io.comparator.LastModifiedFileComparator.*;

import java.io.File;
import java.util.Arrays;

public class FileSortLastModified {
    public static void main(String[] args) {
        File dir = new File(System.getProperty("user.home"));
        File[] files = dir.listFiles();

        if (files != null) {
            // Sort files in ascending order based on file's last
            // modification date.
            System.out.println("Ascending order.");
            Arrays.sort(files, LASTMODIFIED_COMPARATOR);
            FileSortLastModified.displayFileOrder(files);

            System.out.println("------------------------------------");

            // Sort files in descending order based on file's last
            // modification date.
            System.out.println("Descending order.");
            Arrays.sort(files, LASTMODIFIED_REVERSE);
            FileSortLastModified.displayFileOrder(files);
        }
    }

    private static void displayFileOrder(File[] files) {
        for (File file : files) {
            System.out.printf("%2$td/%2$tm/%2$tY - %s%n", file.getName(),
                file.lastModified());
        }
    }
}

Here are the example results produced by the code snippet:

Ascending order.
15/12/2016 - ntuser.dat.LOG1
15/12/2016 - ntuser.ini
15/12/2016 - .m2
18/12/2016 - Contacts
22/12/2016 - Videos
01/01/2017 - VirtualBox VMs
02/01/2017 - Desktop
02/01/2017 - Documents
------------------------------------------
Descending order.
02/01/2017 - Documents
02/01/2017 - Desktop
01/01/2017 - VirtualBox VMs
22/12/2016 - Videos
18/12/2016 - Contacts
15/12/2016 - .m2
15/12/2016 - ntuser.ini
15/12/2016 - ntuser.dat.LOG1

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply