Close

How to sort files by date created in Java?

[Last Updated: May 31, 2018]

Java IO & NIO Java 

In this quick example, we will show how to sort java.io.File by date created.

public class ExampleSortFilesByDate {
  public static void main(String[] args) {
      File dir = new File("d:\\test");
      File[] files = dir.listFiles();
      System.out.println("-- printing files before sort --");
      printFiles(files);
      sortFilesByDateCreated(files);
      System.out.println("-- printing files after sort --");
      printFiles(files);
  }

  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());
      }
  }

  public static void sortFilesByDateCreated (File[] files) {
      Arrays.sort(files, new Comparator<File>() {
          public int compare (File f1, File f2) {
              long l1 = getFileCreationEpoch(f1);
              long l2 = getFileCreationEpoch(f2);
              return Long.valueOf(l1).compareTo(l2);
          }
      });
  }

  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);
      }
  }
}

Output

-- printing files before sort --
2017-04-28T10:00:25.120 - one.txt
2017-04-28T09:59:56.566 - test1.txt
2017-04-28T10:00:09.402 - test2.txt
-- printing files after sort --
2017-04-28T09:59:56.566 - test1.txt
2017-04-28T10:00:09.402 - test2.txt
2017-04-28T10:00:25.120 - one.txt

See Also