How do I find the last modified file in a directory in java?
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With