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

Viewed 240472

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 based on File.lastModified, but I was wondering if there was a better way.

Edit: My current solution, as suggested, is to use an anonymous Comparator:

File[] files = directory.listFiles();

Arrays.sort(files, new Comparator<File>(){
    public int compare(File f1, File f2)
    {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    } });
20 Answers

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().

public String[] getDirectoryList(String path) {
    String[] dirListing = null;
    File dir = new File(path);
    dirListing = dir.list();

    Arrays.sort(dirListing, 0, dirListing.length);
    return dirListing;
}

Here's the Kotlin way of doing it if any one is looking for it :

val filesList = directory.listFiles()

filesList?.let{ list ->
    Arrays.sort(list) { 
        f1, f2 -> f2.lastModified().compareTo(f1.lastModified()) 
    }
}

let array name -> files.


Ascending -> Arrays.sort(files, (o1, o2) -> Long.compare(o1.lastModified(), o2.lastModified()));

Descending -> Arrays.sort(files, (o1, o2) -> Long.compare(o2.lastModified(), o1.lastModified()));

There is a very easy and convenient way to handle the problem without any extra comparator. Just code the modified date into the String with the filename, sort it, and later strip it off again.

Use a String of fixed length 20, put the modified date (long) into it, and fill up with leading zeros. Then just append the filename to this string:

String modified_20_digits = ("00000000000000000000".concat(Long.toString(temp.lastModified()))).substring(Long.toString(temp.lastModified()).length()); 

result_filenames.add(modified_20_digits+temp.getAbsoluteFile().toString());

What happens is this here:

Filename1: C:\data\file1.html Last Modified:1532914451455 Last Modified 20 Digits:00000001532914451455

Filename1: C:\data\file2.html Last Modified:1532918086822 Last Modified 20 Digits:00000001532918086822

transforms filnames to:

Filename1: 00000001532914451455C:\data\file1.html

Filename2: 00000001532918086822C:\data\file2.html

You can then just sort this list.

All you need to do is to strip the 20 characters again later (in Java 8, you can strip it for the whole Array with just one line using the .replaceAll function)

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!

In java 6, the best way is:

  File[] listaArchivos = folder.listFiles();
            Arrays.sort(listaArchivos, new Comparator<File>() {
                @Override
                public int compare(File f1, File f2) {
                    return (f1.lastModified() < f2.lastModified()) ? -1 : ((f1.lastModified() == f2.lastModified()) ? 0 : 1);
                }
            }); 

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.

Related