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

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.


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;
}