How do I find the last modified file in a directory in Java?
Asked Answered
I

9

33

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

Impute answered 14/1, 2010 at 14:23 Comment(1)
Are you asking how to sort by last modified time? Or do you want an algorithm that finds the maximum of last modified time? These seem like obvious solutions; what are you really asking for?Stalinsk
E
53
private File getLatestFilefromDir(String dirPath){
    File dir = new File(dirPath);
    File[] files = dir.listFiles();
    if (files == null || 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];
       }
    }
    return lastModifiedFile;
}
Erbium answered 14/1, 2010 at 14:26 Comment(5)
I'd thought it would be cleaner to use a custom comparator, but this way is faster.Shinleaf
using a comparator is a good practice, but this is just a simple task and could go without it.Erbium
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 ;)Erbium
@Erbium - 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.Bathroom
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.Montgolfier
C
8

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.

Coffeng answered 14/1, 2010 at 14:25 Comment(0)
G
8
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;

...
...

/* Get the newest file for a specific extension */
public File getTheNewestFile(String filePath, String ext) {
    File theNewestFile = null;
    File dir = new File(filePath);
    FileFilter fileFilter = new WildcardFileFilter("*." + ext);
    File[] files = dir.listFiles(fileFilter);

    if (files.length > 0) {
        /** The newest file comes first **/
        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        theNewestFile = files[0]
    }

    return theNewestFile;
}

This works great for me

Guarneri answered 9/9, 2012 at 8:48 Comment(0)
I
3

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

Iodize answered 14/1, 2010 at 14:26 Comment(1)
The comparator doesn't work.Holotype
A
3

Your problem is similar to: How to get only 10 last modified files from directory using Java?

Just change the filter code to have only one File and the accept method should simply compare the two time stamps.

Untested code:

     class TopFileFilter implements FileFilter {

        File topFile;

        public boolean accept(File newF) {
            if(topFile == null)
                topFile = newF;
            else if(newF.lastModified()>topFile.lastModified())
                topFile = newF;
            return false;
        }

    }

Now, call dir.listFiles with an instance of this filter as argument. At the end, the filter.topFile is the last modified file.

Allness answered 16/2, 2011 at 6:46 Comment(0)
H
2

Let's assume that the variable thePath contains the directory we want to search, the following snippet returns the last modified file inside it:

Files.walk(thePath)
.sorted((f1, f2) -> -(int)(f1.toFile().lastModified() - f2.toFile().lastModified()))
.skip(1)
.findFirst()

What it does is:

  • first sort the files by their last modification time in reverse,
  • then skip the directory itself,
  • and finally take the first element in the stream (which is the last modified one).
Handout answered 27/4, 2017 at 21:14 Comment(1)
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Rosariarosario
M
1

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.

Momentary answered 14/1, 2010 at 15:12 Comment(0)
V
1
    String path = "C:\\Work\\Input\\";

    File dir = new File(path);
    File[] files = dir.listFiles();

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

    for (int index = 0; index < files.length; index++) {
        // Print out the name of files in the directory
        System.out.println(files[index].getName());
    }

}
Verbena answered 5/6, 2014 at 7:18 Comment(0)
T
1

Java 8

Optional<Path> findLastModifiedFile(Path directory) throws IOException {
    return Files.list(directory)
            .max(this::compareLastModified);
}

int compareLastModified(Path p1, Path p2) {
    try {
        return Files.getLastModifiedTime(p1).compareTo(Files.getLastModifiedTime(p2));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Tickler answered 20/3, 2018 at 18:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.