Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 814
jumar Avatar asked Jan 14 '10 14:01

jumar


People also ask

How do I get last modified?

For legacy IO, we can use the File. lastModified() to get the last modified time; the method returns a long value measured in milliseconds since the [epoch time](https://en.wikipedia.org/wiki/Epoch_(computing). We can use SimpleDateFormat to make it a more human-readable format.

How do I find the last modified date of a file?

The lastModified() method of the File class returns the last modified time of the file/directory represented by the current File object. You can get the last modified time of a particular file using this method.

How do you check if a file has been modified in Java?

Thankfully, the File class comes with a handy method called lastModified(). This method returns the last modified time of the file denoted by an abstract pathname. As we can see, we use the Java 8 Stream API to loop through an array of files.


1 Answers

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; } 
like image 84
Bozho Avatar answered Sep 30 '22 19:09

Bozho