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

最后修改: 2016年 12月 1日


1. Overview


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:


import java.nio.file.*;

2. Why Use WatchService


A common example to understand what the service does is actually the 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.


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


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?


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


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:


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.


3.1. The 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


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.


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


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.


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,它将不会捕获更多的事件:


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()) {

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


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"));


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

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


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.