views:

175

answers:

4

How do I find the last modified file in a directory in java?

+5  A: 

Combine these two:

  1. You can get the last modified time of a File using File.lastModified().
  2. To list all of the files in a directory, use File.listFiles().

Note that in Java the java.io.File object is used for both directories and files.

matt b
+2  A: 

You can retrieve the time of the last modification using the File.lastModified() method. My suggested solution would be to implement a custom Comparator that sorts in lastModified()-order and insert all the Files in the directory in a TreeSet that sorts using this comparator.

Untested example:

SortedSet<File> modificationOrder = new TreeSet<File>(new Comparator<File>() {
    public int compare(File a, File b) {
        return a.lastModified() - b.lastModified();
    }
});

for (File file : myDir.listFiles()) {
    modificationOrder.add(file);
}

File last = modificationOrder.last();

The solution suggested by Bozho is probably faster if you only need the last file. On the other hand, this might be useful if you need to do something more complicated.

Emil H
+5  A: 
File dir = new File("/path/to/dir");

File[] files = dir.listFiles();
if (files.length == 0) {
    return null;
}

File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
   if (lastModifiedfile.lastModified() < files[i].lastModified) {
       lastModifiedFile = files[i];
   }
}

You could use a Comparator, but it is an overhead for a simple task such as this.

Bozho
I'd thought it would be cleaner to use a custom comparator, but this way is faster.
Steve B.
using a comparator is a good practice, but this is just a simple task and could go without it.
Bozho
no. the greater the long value is, the later the file is modified. If that was the reason for the downvote, feel free to undo it ;)
Bozho
@Bozho - using a comparator is no more "good practice", than using the `int` type is "good practice". The strongest you can say is that comparators are a good (partial) solution for many programming problems.
Stephen C
You could get an index out of bounds if the directory is empty. You should not assign files[0] to lastModifiedFile outside of the loop.
Steve Kuo
A: 

The comparator in Emil's solution would be cleaner this way

public int compare(File a, File b) {
    if ((a.lastModified() < b.lastModified())) {
        return 1;
    } else if ((a.lastModified() > b.lastModified())) {
        return -1;
    } 
    return 0;
}

Casting (a.lastModified() - b.lastModified()) to int can produce unexpected results.

Vinodh Ramasubramanian