0

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Paul Taylor
  • 13,411
  • 42
  • 184
  • 351
  • 3
    Possible duplicate of [java : Sort Files based on Creation Date](https://stackoverflow.com/questions/10249822/java-sort-files-based-on-creation-date) – Vasan Apr 04 '18 at 19:38
  • 1
    You seem using File (java.io) and not Path (java.nio). `nio2` tag refers to `java.nio` – davidxxx Apr 04 '18 at 19:42
  • @davidxxx i use both, just thought an answer using nio2 would be more likley – Paul Taylor Apr 04 '18 at 20:00
  • 1
    I think you need to take a closer look at the duplicate question. There is a version of it using Apache but the main question pretty much gives what you need - it doesn't use any libs. – Vasan Apr 04 '18 at 20:00
  • @Vasan the answer below is better – Paul Taylor Apr 05 '18 at 09:04

1 Answers1

2

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);
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
niekname
  • 2,528
  • 1
  • 13
  • 27