javafilesortingnio2

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.


Solution

  • 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);