Java - get the newest file in a directory?
file-io, filesystems, java
Solution
The following code returns the last modified file or folder:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required `Java 8` or newer due to the lambda expression.
Problem
Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?