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

jumar picture jumar · Jan 14, 2010 · Viewed 51.3k times · Source

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

Answer

Bozho picture Bozho · Jan 14, 2010
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;
}