Java - get the newest file in a directory?

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.


In Java 8:

Path dir = Paths.get("./path/somewhere");  // specify your directory

Optional<Path> lastFilePath = Files.list(dir)    // here we get the stream with full directory listing
    .filter(f -> !Files.isDirectory(f))  // exclude subdirectories from listing
    .max(Comparator.comparingLong(f -> f.toFile().lastModified()));  // finally get the last file using simple comparator by lastModified field

if ( lastFilePath.isPresent() ) // your folder may be empty
{
    // do your code here, lastFilePath contains all you need
}