Close

How to sort files by date created in Java?

[Last Updated: Aug 25, 2020]

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 --
2015-12-11T00:24:52.782 - data.xml
2011-02-21T00:25:38.137 - info.txt
2019-08-07T00:26:27.271 - manual.pdf

-- printing files after sort ascending --
2011-02-21T00:25:38.137 - info.txt
2015-12-11T00:24:52.782 - data.xml
2019-08-07T00:26:27.271 - manual.pdf

-- printing files after sort descending --
2019-08-07T00:26:27.271 - manual.pdf
2015-12-11T00:24:52.782 - data.xml
2011-02-21T00:25:38.137 - info.txt

See Also