Wednesday 11 March 2020

List files by their created time

Using a comparator, we can sort the files by their creation time.

FileCreateTimeComparator.java
package com.sample.app.comparator;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Comparator;

public class FileCreateTimeComparator implements Comparator<File> {

 @Override
 public int compare(File file1, File file2) {

  long file1CreatedTime = getCreatedTime(file1);
  long file2CreatedTime = getCreatedTime(file2);

  if (file1CreatedTime > file2CreatedTime)
   return 1;
  else if (file1CreatedTime < file2CreatedTime)
   return -1;
  return 0;
 }

 private static long getCreatedTime(File file) {
  Path path = file.toPath();
  FileTime creationTime;
  try {
   creationTime = (FileTime) Files.getAttribute(path, "creationTime");
   return creationTime.toMillis();
  } catch (IOException e) {
   return Long.MAX_VALUE;
  }

 }
}

App.java

package com.sample.app;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Date;

import com.sample.app.comparator.FileCreateTimeComparator;

public class App {

 private static void printFiles(File[] files) {
  for (File file : files) {
   Date date = getCreatedTime(file);
   System.out.println(date + "\t" + file.getName());
  }
 }

 private static Date getCreatedTime(File file) {
  Path path = file.toPath();
  FileTime creationTime;
  try {
   creationTime = (FileTime) Files.getAttribute(path, "creationTime");
   Date date = new Date();
   date.setTime(creationTime.toMillis());
   return date;
  } catch (IOException e) {
   return null;
  }

 }

 public static File[] sortByCreatedTime(String directoryPath) {
  File directory = new File(directoryPath);

  File[] files = directory.listFiles();

  Arrays.sort(files, new FileCreateTimeComparator());
  return files;
 }

 public static void main(String[] args) {
  String directoryPath = "/Users/krishna/Documents/TechnicalDocuments";

  File[] files1 = sortByCreatedTime(directoryPath);

  printFiles(files1);
 }

}


You may like

No comments:

Post a Comment