Answers for "java file sorting using date or time"

0

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);
      }
  }
}
Posted by: Guest on August-13-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language