Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last modified date and time of a directory in java

See, the problem is that in Java, we can get lastmodified date by filename.lastModified(). But in Windows, what is happening is that whenever a file is modifed, only that file's date and time are getting modified, not the whole folder's. So I want to know when was the last time even one single file was modified in that folder, using Java?

like image 953
Vasanth Kumar Avatar asked Sep 03 '12 13:09

Vasanth Kumar


1 Answers

Find the latest (largest) lastModified() in the directory's files, or if there are none use the directory's itself:

public static Date getLastModified(File directory) {
    File[] files = directory.listFiles();
    if (files.length == 0) return new Date(directory.lastModified());
    Arrays.sort(files, new Comparator<File>() {
        public int compare(File o1, File o2) {
            return new Long(o2.lastModified()).compareTo(o1.lastModified()); //latest 1st
        }});
    return new Date(files[0].lastModified());
}

FYI this code has been tested (and it works).

like image 120
Bohemian Avatar answered Oct 21 '22 02:10

Bohemian