Wednesday 11 March 2020

Sort the files by their last modified date

Approach 1: Using Comparator.
public class FileModifiedDateComparator implements Comparator<File> {

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

  long file1ModifiedDate = file1.lastModified();
  long file2ModifiedDate = file2.lastModified();

  if (file1ModifiedDate > file2ModifiedDate)
   return 1;
  else if (file1ModifiedDate < file2ModifiedDate)
   return -1;
  return 0;
 }

}

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

 File[] files = directory.listFiles();

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

Approach 2: Using Comparator.comparingLong.
File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));

Find the below working application.

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

import java.io.File;
import java.util.Comparator;

public class FileModifiedDateComparator implements Comparator<File> {

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

  long file1ModifiedDate = file1.lastModified();
  long file2ModifiedDate = file2.lastModified();

  if (file1ModifiedDate > file2ModifiedDate)
   return 1;
  else if (file1ModifiedDate < file2ModifiedDate)
   return -1;
  return 0;
 }

}

App.java
package com.sample.app;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import com.sample.app.comparator.FileModifiedDateComparator;

public class App {

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

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

  File[] files = directory.listFiles();

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

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

  File[] files = directory.listFiles();

  Arrays.sort(files, Comparator.comparingLong(File::lastModified));
  return files;
 }

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

  File[] files1 = sortByModifiedDate_Approach1(directoryPath);
  File[] files2 = sortByModifiedDate_Approach1(directoryPath);

  printFiles(files1);
  printFiles(files2);
 }

}



You may like

No comments:

Post a Comment