Close

How to sort files by date created in Java?

[Last Updated: Oct 29, 2025]

Java IO & NIO Java 

This example shows how to sort java.io.File by date created in ascending and descending orders.

public class ExampleSortFilesByDate {
    public static void main(String[] args) {

        File dir = new File("d:\\test");
        File[] files = dir.listFiles();
        if (files == null) {
            System.out.println("No files under d:\\test");
            return;
        }
        System.out.println("-- printing files before sort --");
        printFiles(files);

        System.out.println();
        sortFilesByDateCreated(files, false);
        System.out.println("-- printing files after sort ascending --");
        printFiles(files);

        System.out.println();
        files = dir.listFiles();
        sortFilesByDateCreated(files, true);
        System.out.println("-- printing files after sort descending --");
        printFiles(files);
    }

    public static void sortFilesByDateCreated(File[] files, boolean descending) {
        Comparator<File> comparator =
                Comparator.comparingLong(ExampleSortFilesByDate::getFileCreationEpoch);
        if (descending) {
            comparator = comparator.reversed();
        }
        Arrays.sort(files, comparator);
    }

    public static long getFileCreationEpoch(File file) {
        try {
            BasicFileAttributes attr = Files.readAttributes(file.toPath(),
                    BasicFileAttributes.class);
            return attr.creationTime()
                       .toInstant()
                       .toEpochMilli();
        } catch (IOException e) {
            throw new RuntimeException(file.getAbsolutePath(), e);
        }
    }

    private static void printFiles(File[] files) {
        for (File file : files) {
            long m = getFileCreationEpoch(file);
            Instant instant = Instant.ofEpochMilli(m);
            LocalDateTime date = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
            System.out.println(date + " - " + file.getName());
        }
    }
}

Output

-- printing files before sort --
2025-10-28T17:04:09.832 - myTestFile.txt
2025-10-25T14:19:29.725 - one.txt
2025-10-25T14:19:53.196 - testDir1
2025-10-25T14:20:04.151 - testDir2
2025-10-25T14:19:37.969 - two.txt

-- printing files after sort ascending --
2025-10-25T14:19:29.725 - one.txt
2025-10-25T14:19:37.969 - two.txt
2025-10-25T14:19:53.196 - testDir1
2025-10-25T14:20:04.151 - testDir2
2025-10-28T17:04:09.832 - myTestFile.txt

-- printing files after sort descending --
2025-10-28T17:04:09.832 - myTestFile.txt
2025-10-25T14:20:04.151 - testDir2
2025-10-25T14:19:53.196 - testDir1
2025-10-25T14:19:37.969 - two.txt
2025-10-25T14:19:29.725 - one.txt

See Also