-2

I want to sort files in java based on last modification time. But it should be lightning quick.

File[] fileList = null;

try {
    File rootFolder = new File(dir);

    if (rootFolder.isDirectory()) {
        fileList = rootFolder.listFiles();
    }



Arrays.sort(fileList, new Comparator<File>() {
    public int compare(File f1, File f2) {
        return Long.compare(f1.lastModified(), f2.lastModified());
    }
});
} catch(Exception e) {
    System.out.println("Not a valid directory " + dir);
}
Karan mehta
  • 89
  • 2
  • 10
  • 1
    Your code is not doing any sorting. Please [edit] it and add what you have tried. Does it work? Is it fast? How do you measure? –  Feb 13 '19 at 09:12
  • 1
    I would use [NIO](https://docs.oracle.com/javase/tutorial/essential/io/walk.html) for that. [Here](https://www.programcreek.com/java-api-examples/?class=java.nio.file.Files&method=walkFileTree) are some good examples just for start... – dbl Feb 13 '19 at 09:12
  • @Lutz Horn .... Done – Karan mehta Feb 13 '19 at 09:16
  • https://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified – Dereje Goshu Feb 13 '19 at 10:12

1 Answers1

1

You can try this code from Sorting files Program

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

public class ListFilesByDate {

   public static void main(String[] args) {
      File dir = new File("/tmp/code");
      File[] files = dir.listFiles();
      Arrays.sort(files, new Comparator<File>(){
        public int compare(File f1, File f2) {
          return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified());
        } 
      });

      for(File file: files) {
        System.out.println(file.getName());
      }
   }
}
Narendar Reddy M
  • 1,499
  • 1
  • 11
  • 18