Find the Last Modified File in a Directory with Java

1. Overview

In this quick tutorial, we’re going to take a close look at how to find the last modified file in a specific directory in Java.

First, we’ll start with the legacy IO and the modern NIO APIs. Then, we’ll see how to use the Apache Commons IO library to accomplish the same thing.

2. Using the java.io API

The legacy java.io package provides the File class to encapsulate an abstract representation of file and directory pathnames.

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.

Let’s now look at how we can use the java.io.File class to achieve the intended purpose:

public static File findUsingIOApi(String sdir) {
    File dir = new File(sdir);
    if (dir.isDirectory()) {
        Optional<File> opFile = Arrays.stream(dir.listFiles(File::isFile))
          .max((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
        if (opFile.isPresent()){
            return opFile.get();
        }
    }
    return null;
}

As we can see, we use the Java 8 Stream API to loop through an array of files. Then, we invoke the max() operation to get the file with the most recent modifications.

Notice that we use an Optional instance to encapsulate the last modified file.

Bear in mind that this approach is considered old fashion and out of date. However, we can use it if we want to stay compatible with the Java legacy IO world.

3. Using the java.nio API

The introduction of the NIO API is a turning point for file system management. The new version NIO.2 shipped in Java 7 comes with a set of enhanced features for better file management and manipulation.

As a matter of fact, the java.nio.file.Files class offers great flexibility when it comes to manipulating files and directories in Java.

So, let’s see how we can make use of the Files class to get the last modified file in a directory:

public static Path findUsingNIOApi(String sdir) throws IOException {
    Path dir = Paths.get(sdir);
    if (Files.isDirectory(dir)) {
        Optional<Path> opPath = Files.list(dir)
          .filter(p -> !Files.isDirectory(p))
          .sorted((p1, p2)-> Long.valueOf(p2.toFile().lastModified())
            .compareTo(p1.toFile().lastModified()))
          .findFirst();
        if (opPath.isPresent()){
            return opPath.get();
        }
    }
    return null;
}

Similarly to the first example, we rely on the Steam API to get only files. Then, we sort our files based on the last modified time with the help of a lambda expression.

4. Using Apache Commons IO

The Apache Commons IO has taken file system management to the next level. It provides a set of handy classes, file comparators, file filters, and much more.

Fortunately for us, the library offers the LastModifiedFileComparator class which can be used as a comparator to sort an array of files by their last modified time.

Firstly, we need to add the commons-io dependency in our pom.xml:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>

Lastly, let’s showcase how to find the last modified file in a folder using Apache Commons IO:

public static File findUsingCommonsIO(String sdir) {
    File dir = new File(sdir);
    if (dir.isDirectory()) {
        File[] dirFiles = dir.listFiles((FileFilter)FileFilterUtils.fileFileFilter());
        if (dirFiles != null && dirFiles.length > 0) {
            Arrays.sort(dirFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
            return dirFiles[0];
        }
     }
    return null;
}

As shown above, we use the singleton instance LASTMODIFIED_REVERSE to sort our array of files in reverse order.

Since the array is reversely sorted, then the last modified file is the first element of the array.

5. Conclusion

In this tutorial, we explored different ways to find the last modified file in a particular directory. Along the way, we used APIs that are part of the JDK and the Apache Commons IO external library.

As always, the complete code source of the examples is available over on GitHub.

The post Find the Last Modified File in a Directory with Java first appeared on Baeldung.

        


电子产品 排行榜


Gurmandise 哆啦A梦 铜锣烧 手机手环

IT電腦補習 java補習 為大家配對電腦補習,IT freelance, 私人老師, PHP補習,CSS補習,XML,Java補習,MySQL補習,graphic design補習,中小學ICT補習,一對一私人補習和Freelance自由工作配對。
立刻註冊及報名電腦補習課程吧!

facebook 查詢:
24 hours enquiry facebook channel :
https://www.facebook.com/itteacheritfreelance/?ref=aymt_homepage_panel

Be the first to comment

Leave a Reply

Your email address will not be published.


*