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

后端 未结 17 1054
-上瘾入骨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:20

    A slightly more modernized version of the answer of @jason-orendorf.

    Note: this implementation keeps the original array untouched, and returns a new array. This might or might not be desirable.

    files = Arrays.stream(files)
            .map(FileWithLastModified::ofFile)
            .sorted(comparingLong(FileWithLastModified::lastModified))
            .map(FileWithLastModified::file)
            .toArray(File[]::new);
    
    private static class FileWithLastModified {
        private final File file;
        private final long lastModified;
    
        private FileWithLastModified(File file, long lastModified) {
            this.file = file;
            this.lastModified = lastModified;
        }
    
        public static FileWithLastModified ofFile(File file) {
            return new FileWithLastModified(file, file.lastModified());
        }
    
        public File file() {
            return file;
        }
    
        public long lastModified() {
            return lastModified;
        }
    }
    

    But again, all credits to @jason-orendorf for the idea!

提交回复
热议问题