Best way to list files in Java, sorted by Date Modified?

后端 未结 17 1061
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:51

I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list ba

17条回答
  •  孤城傲影
    2020-11-22 12:40

    You can use Apache LastModifiedFileComparator library

     import org.apache.commons.io.comparator.LastModifiedFileComparator;  
    
    
    File[] files = directory.listFiles();
            Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
            for (File file : files) {
                Date lastMod = new Date(file.lastModified());
                System.out.println("File: " + file.getName() + ", Date: " + lastMod + "");
            }
    

提交回复
热议问题