java file sorting using date or time

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

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source