简体   繁体   中英

How do I sort results of File.listFiles() by creation date?

In Java Sort how do I sort results of File.listFiles() by creation date?

I did have:

files = reportFolder.listFiles(new ReportFolderFilter()));
Collections.reverse(files);

But this will only sort them in reverse alphabetical order not creation date.

I would like a solution that does not rely on Apache Commons.

you can use Collections.sort or Arrays.sort or List.sort

You can get the creation date of a file by using java nio Files. readAttributes()

Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(final File o1, final File o2) {
            try {
                BasicFileAttributes f1Attr = Files.readAttributes(Paths.get(f1.toURI()), BasicFileAttributes.class);
                BasicFileAttributes f2Attr = Files.readAttributes(Paths.get(f2.toURI()), BasicFileAttributes.class);
                return f1Attr.creationTime().compareTo(f2Attr.creationTime());
            } catch (IOException e) {
                return 0;
            }
        }
    });

Or using Comparator.comparing:

Comparator<File> comparator = Comparator.comparing(file -> {
    try {
        return Files.readAttributes(Paths.get(file.toURI()), BasicFileAttributes.class).creationTime();
    } catch (IOException e) {
        return null;
    }
});

Arrays.sort(files, comparator);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM