Java WatchService Example

In this post we will explain how to monitor changes in a directory by using the Java WatchService. The WatchService allows you to monitor for changes in a path. In the post we will explain what events you can watch for, how to register for events and then a full Java WatchService example.

What events can I watch for:

The WatchService API allows you to watch for the following changes:

  • ENTRY_CREATE: Watches for new files
  • ENTRY_MODIFY: Watches for files that have been modified
  • ENTRY_DELETE: Watches for files that have been deleted
  • OVERFLOW: Special event which indicates that events might have been lost or discarded.  You do not have to register for the this event to receive it

Register to watch events:

The code snippet below provides an example of how you can register a WatchService to watch for events on a path:

Java WatchService Example – Watching for changing events:

Below is the full example showing how to handle the file change events.

A few points about the above example:

  • Line 4: Register a watchService to the path object so that we can monitor new files created or files being modified on that path (/tmp/dir1).
  • Line 9: If a new file has been added or a file modified then this will return immediately otherwise it will block for 2 seconds waiting for new events to occur.
  • Line 11: If the watchKey is null this means no changes have occurred.
  • Line 12: Poll the events so that we can process the files which have changed or have been created.
  • Line 13-14:Get the event type (file created or modified) and the path of the file.
  • Line 19-23: Do the necessary business processing based on the event.
  • Line 25: Reset the watchKey in order to retrieve new events.
  • Line 27-31: If you failed to reset the watchKey then you won’t be able to get new events this could be beacuse the directory was deleted or permissions have changed.

In conclusion, I hope this has helped you understand the WatchService a little better.

Similar posts:

  1. How to move a file in Java
  2. List files in a directory
  3. How to get file in a AWS S3 Bucket
  4. How to delete a file in Java


  1. Java 8 WatchService API Documentation
  2. Watching a directory for changes Java tutorial

Leave a Reply