A Guide to WatchService in Java NIO2 – Java NIO2中的WatchService指南

最后修改: 2016年 12月 1日

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

1. Overview

1.概述

In this article, we are going to explore the WatchService interface of Java NIO.2 filesystem APIs. This is one of the lesser known features of the newer IO APIs that were introduced in Java 7 alongside FileVisitor interface.

在这篇文章中,我们将探讨Java NIO.2文件系统API的WatchService接口。这是在Java 7中与FileVisitor接口一起引入的较新的IO API中较少为人所知的功能之一。

To use the WatchService interface in your applications, you need to import the appropriate classes:

要在你的应用程序中使用WatchService接口,你需要导入相应的类。

import java.nio.file.*;

2. Why Use WatchService

2.为什么使用WatchService

A common example to understand what the service does is actually the IDE.

要了解服务的内容,一个常见的例子其实是IDE。

You might have noticed that the IDEs always detects a change in source code files that happen outside itself. Some IDE’s inform you using a dialog box so that you can choose to reload the file from the filesystem or not, others simply update the file in the background.

你可能已经注意到,IDE总是检测到发生在自身之外的源代码文件的变化。一些IDE使用对话框通知你,这样你就可以选择是否从文件系统中重新加载文件,其他的IDE只是在后台更新文件。

Similarly, newer frameworks such as Play also does hot reloading of the application code by default – whenever you’re performing edits from any editor.

同样,较新的框架,如Play,也会默认对应用程序的代码进行热重载–只要你在任何编辑器中进行编辑。

These applications employ a feature called file change notification that is available in all filesystems.

这些应用程序采用了一种叫做文件更改通知的功能,在所有文件系统中都可用。

Basically, we can write code to poll the filesystem for changes on specific files and directories. However, this solution is not scalable especially if the files and directories reach the hundreds and thousands.

基本上,我们可以写代码来轮询文件系统中特定文件和目录的变化。然而,这种解决方案是不可扩展的,特别是当文件和目录达到数百和数千时。

In Java 7 NIO.2, the WatchService API provides a scalable solution for monitoring directories for changes. It has a clean API and is so well optimized for performance that we don’t need to implement our own solution.

在Java 7 NIO.2中,WatchService API提供了一个可扩展的解决方案来监控目录的变化。它有一个干净的API,并且对性能进行了很好的优化,我们不需要实现我们自己的解决方案。

3. How Does the Watchservice Work?

3.观察服务是如何工作的?

To use the WatchService features, the first step is to create a WatchService instance using the java.nio.file.FileSystems class:

要使用WatchService功能,第一步是使用java.nio.file.FileSystems类创建一个WatchService实例。

WatchService watchService = FileSystems.getDefault().newWatchService();

Next, we have to create the path to the directory we want to monitor:

接下来,我们必须创建我们要监控的目录的路径。

Path path = Paths.get("pathToDir");

After this step, we have to register the path with watch service. There are two important concepts to understand at this stage. The StandardWatchEventKinds class and the WatchKey class. Take a look at the following registration code just to understand where each fall. We will follow this with explanations of the same:

在这一步之后,我们必须向观察服务注册路径。在这个阶段,有两个重要的概念需要理解。StandardWatchEventKinds类和WatchKey类。看一下下面的注册代码,只是为了了解每个人的落脚点。我们将在此基础上对其进行解释。

WatchKey watchKey = path.register(
  watchService, StandardWatchEventKinds...);

Notice only two important things here: First, the path registration API call takes the watch service instance as the first parameter followed by variable arguments of StandardWatchEventKinds. Secondly, the return type of the registration process is a WatchKey instance.

注意这里只有两件重要的事情。首先,路径注册API调用将手表服务实例作为第一个参数,然后是StandardWatchEventKinds的可变参数。其次,注册过程的返回类型是一个WatchKey实例。

3.1. The StandardWatchEventKinds

3.1.StandardWatchEventKinds

This is a class whose instances tell the watch service the kinds of events to watch for on the registered directory. There are currently four possible events to watch for:

这是一个类,其实例告诉观察服务在注册的目录上要观察的事件种类。目前有四种可能的事件可供观察。

  • StandardWatchEventKinds.ENTRY_CREATE – triggered when a new entry is made in the watched directory. It could be due to the creation of a new file or renaming of an existing file.
  • StandardWatchEventKinds.ENTRY_MODIFY – triggered when an existing entry in the watched directory is modified. All file edit’s trigger this event. On some platforms, even changing file attributes will trigger it.
  • StandardWatchEventKinds.ENTRY_DELETE – triggered when an entry is deleted, moved or renamed in the watched directory.
  • StandardWatchEventKinds.OVERFLOW – triggered to indicate lost or discarded events. We won’t focus much on it

3.2. The WatchKey

3.2.WatchKey

This class represents the registration of a directory with the watch service. Its instance is returned to us by the watch service when we register a directory and when we ask the watch service if any events we registered for have occurred.

这个类代表了一个目录在观察服务中的注册。当我们注册一个目录时,以及当我们询问观察服务是否有任何我们注册的事件发生时,观察服务会将其实例返回给我们。

Watch service offers us no callback methods which are called whenever an event occurs. We can only poll it in a number of ways to find this information.

观察服务没有为我们提供回调方法,每当事件发生时都会被调用。我们只能通过一些方式来轮询它,以找到这些信息。

We can use the poll API:

我们可以使用poll API。

WatchKey watchKey = watchService.poll();

This API call returns right away. It returns the next queued watch key any of whose events have occurred or null if no registered events have occurred.

这个API调用会立即返回。它返回下一个排队的手表钥匙,其中任何一个事件已经发生,如果没有注册的事件发生,则返回空。

We can also use an overloaded version that takes a timeout argument:

我们还可以使用一个重载版本,它需要一个timeout参数。

WatchKey watchKey = watchService.poll(long timeout, TimeUnit units);

This API call is similar to the previous one in return value. However, it blocks for timeout units of time to give more time within which an event may occur instead of returning null right away.

这个API调用在返回值上与前一个相似。然而,它阻断了timeout单位的时间,以提供更多可能发生事件的时间,而不是立即返回null。

Finally, we can use the take API:

最后,我们可以使用take API。

WatchKey watchKey = watchService.take();

This last approach simply blocks until an event occurs.

这最后一种方法只是简单地阻断,直到事件发生。

We must note something very important here: when the WatchKey instance is returned by either of the poll or take APIs, it will not capture more events if it’s reset API is not invoked:

我们必须注意一些非常重要的事情。WatchKey实例被polltake API返回时,如果不调用它的重置API,它将不会捕获更多的事件:

watchKey.reset();

This means that the watch key instance is removed from the watch service queue every time it is returned by a poll operation. The reset API call puts it back in the queue to wait for more events.

这意味着,每次轮询操作返回时,观察键实例都会从观察服务队列中移除。reset API调用将它放回队列中,以等待更多的事件。

The most practical application of the watcher service would require a loop within which we continuously check for changes in the watched directory and process accordingly. We can use the following idiom to implement this:

观察者服务最实际的应用需要一个循环,在这个循环中我们不断地检查被观察的目录中的变化,并进行相应的处理。我们可以使用下面的成语来实现这一点。

WatchKey key;
while ((key = watchService.take()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
        //process
    }
    key.reset();
}

We create a watch key to store the return value of the poll operation. The while loop will block until the conditional statement returns with either a watch key or null.

我们创建一个观察键来存储轮询操作的返回值。while循环将阻塞,直到条件语句返回一个watch key或null。

When we get a watch key, then the while loop executes the code inside it. We use the WatchKey.pollEvents API to return a list of events that have occurred. We then use a for each loop to process them one by one.

当我们得到一个watch key,然后while循环执行里面的代码。我们使用WatchKey.pollEvents API来返回一个已经发生的事件列表。然后我们使用for each循环来逐一处理它们。

After all the events are processed, we must call the reset API to enqueue the watch key again.

在处理完所有的事件后,我们必须调用reset API来再次排队等待观察键。

4. Directory Watching Example

4.目录观察实例

Since we have covered the WatchService API in the previous subsection and how it works internally and also how we can use it, we can now go ahead and look at a complete and practical example.

由于我们在上一小节中已经介绍了WatchService API,以及它在内部是如何工作的,还有我们如何使用它,我们现在可以继续看一个完整而实用的例子。

For portability reasons, we are going to watch for activity in the user home directory, which should be available on all modern operating systems.

出于可移植性的原因,我们将观察用户主目录中的活动,该目录在所有现代操作系统上都应该是可用的。

The code contains only a few lines of code so we will just keep it in the main method:

这段代码只包含几行代码,所以我们只把它放在主方法中。

public class DirectoryWatcherExample {

    public static void main(String[] args) {
        WatchService watchService
          = FileSystems.getDefault().newWatchService();

        Path path = Paths.get(System.getProperty("user.home"));

        path.register(
          watchService, 
            StandardWatchEventKinds.ENTRY_CREATE, 
              StandardWatchEventKinds.ENTRY_DELETE, 
                StandardWatchEventKinds.ENTRY_MODIFY);

        WatchKey key;
        while ((key = watchService.take()) != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.println(
                  "Event kind:" + event.kind() 
                    + ". File affected: " + event.context() + ".");
            }
            key.reset();
        }
    }
}

And that is all we really have to do. Now you can run the class to start watching a directory.

而这就是我们真正要做的。现在你可以运行这个类来开始观察一个目录。

When you navigate to the user home directory and perform any file manipulation activity like creating a file or directory, changing contents of a file or even deleting a file, it will all be logged at the console.

当你导航到用户主目录并执行任何文件操作活动,如创建文件或目录、改变文件内容甚至删除文件,都会在控制台记录下来。

For instance, assuming you go to user home, right click in space, select `new – > file` to create a new file and then name it testFile. Then you add some content and save. The output at the console will look like this:

例如,假设你进入用户主页,在空间点击右键,选择`new – > file`创建一个新文件,然后将其命名为testFile。然后你添加一些内容并保存。控制台的输出将看起来像这样。

Event kind:ENTRY_CREATE. File affected: New Text Document.txt.
Event kind:ENTRY_DELETE. File affected: New Text Document.txt.
Event kind:ENTRY_CREATE. File affected: testFile.txt.
Event kind:ENTRY_MODIFY. File affected: testFile.txt.
Event kind:ENTRY_MODIFY. File affected: testFile.txt.

Feel free to edit the path to point to any directory you want to watch.

请自由编辑路径,使其指向你想看的任何目录。

5. Conclusion

5.结论

In this article, we have explored some of the less commonly used features available in the Java 7 NIO.2 – filesystem APIs, particularly the WatchService interface.

在这篇文章中,我们探讨了Java 7 NIO.2中的一些不太常用的功能–文件系统API,特别是WatchService接口。

We have also managed to go through the steps of building a directory watching application to demonstrate the functionality.

我们还设法通过建立一个目录观察应用程序的步骤来演示该功能。

And, as always, the full source code for the examples used in this article is available in the Github project.

而且,像往常一样,本文中使用的例子的完整源代码可在Github项目中获得。