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

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

    You can try guava Ordering:

    Function<File, Long> getLastModified = new Function<File, Long>() {
        public Long apply(File file) {
            return file.lastModified();
        }
    };
    
    List<File> orderedFiles = Ordering.natural().onResultOf(getLastModified).
                              sortedCopy(files);
    
    0 讨论(0)
  • 2020-11-22 12:27
    Collections.sort(listFiles, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.compare(f1.lastModified(), f2.lastModified());
            }
        });
    

    where listFiles is the collection of all files in ArrayList

    0 讨论(0)
  • 2020-11-22 12:28

    I think your solution is the only sensible way. The only way to get the list of files is to use File.listFiles() and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a Comparator that uses File.lastModified() and pass this, along with the array of files, to Arrays.sort().

    0 讨论(0)
  • 2020-11-22 12:28

    What's about similar approach, but without boxing to the Long objects:

    File[] files = directory.listFiles();
    
    Arrays.sort(files, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return Long.compare(f1.lastModified(), f2.lastModified());
        }
    });
    
    0 讨论(0)
  • 2020-11-22 12:34

    There is also a completely different way which may be even easier, as we do not deal with large numbers.

    Instead of sorting the whole array after you retrieved all filenames and lastModified dates, you can just insert every single filename just after you retrieved it at the right position of the list.

    You can do it like this:

    list.add(1, object1)
    list.add(2, object3)
    list.add(2, object2)
    

    After you add object2 to position 2, it will move object3 to position 3.

    0 讨论(0)
  • 2020-11-22 12:35

    In Java 8:

    Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));

    0 讨论(0)
提交回复
热议问题