Find the Last Modified File in a Directory with Java – 用Java查找一个目录中最后修改的文件

最后修改: 2020年 9月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

在这个快速教程中,我们将仔细研究如何在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.

首先,我们将从传统IO现代NIO的API开始。然后,我们将看到如何使用Apache Commons IO库来完成同样的事情。

2. Using the java.io API

2.使用java.ioAPI

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

传统的java.io包提供了File类来封装文件和目录路径名的抽象表示。

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.

值得庆幸的是,文件类附带了一个方便的方法,叫做lastModified()。该方法返回由抽象路径名表示的文件的最后修改时间

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

现在让我们看看如何使用java.io.File类来达到预期目的。

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.

正如我们所看到的,我们使用Java 8 Stream API来循环浏览一个文件阵列。然后,我们调用max() 操作来获得最近修改的文件

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

注意,我们使用一个Optional实例来封装最后修改的文件。

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.

请记住,这种方法被认为是老式的、过时的。然而,如果我们想与Java遗留的IO世界保持兼容,我们可以使用它

3. Using the java.nio API

3.使用java.nioAPI

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.

NIO API的引入是文件系统管理的一个转折点。新版本NIO.2搭载在Java 7中,具有一系列增强的功能,可以实现更好的文件管理和操作。

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

事实上,java.nio.file.Files类在Java中操作文件和目录时提供了极大的灵活性。

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

所以,让我们看看如何利用Files 类来获得一个目录中最后修改的文件。

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.

与第一个例子类似,我们只依靠Steam API来获取文件。然后,在lambda表达式的帮助下,我们根据最后修改时间对文件进行排序。

4. Using Apache Commons IO

4.使用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.

Apache Commons IO将文件系统管理提升到了新的水平。它提供了一套方便的类,文件比较器,文件过滤器,以及更多。

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.

幸运的是,该库提供了 LastModifiedFileComparator 类,它可以被用作 比较器,按照文件的最后修改时间对文件阵列进行排序

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

首先,我们需要在我们的pom.xml中添加commons-io依赖项

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

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

最后,让我们展示一下如何使用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.

如上所示,我们使用 单体实例LASTMODIFIED_REVERSE来对我们的文件阵列进行反向排序

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

由于数组是逆向排序的,那么最后修改的文件就是数组的第一个元素。

5. Conclusion

5.总结

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.

在本教程中,我们探索了不同的方法来寻找特定目录中最后修改的文件。在这个过程中,我们使用了属于JDK的API和Apache Commons IO外部库。

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

一如既往,这些示例的完整代码源可在GitHub上获得over