File Change Notification with Watch Service API

Since Java 7, the java.nio.file package adds a feature: file change notification with Watch Service API – java.nio.file.WatchService. Watch Service API allows us to register directories with the watch service, and monitor the directories and files for any changes including creation, deletion, modification etc. The post will briefly introduce the usage of Watch Service API.

Usage of Watch Service API

Step 1: create a new Watch Service

Step 2: register directories to be watched

When registering an object with the watch service, you specify the types of events that you want to monitor:
ENTRY_CREATE – a directory or file is created
ENTRY_DELETE – a directory or file is deleted
ENTRY_MODIFY – a directory or file is modified
OVERFLOW – the event might have been lost or discarded

Step 3: process events

  • Get a queued watch key. Three methods are provided: poll, poll(long, TimeUnit), take
  • Process the pending event list for the key.
  • Retrieve the type of event by using the kind method.
  • Retrieve the file name associated with the event.
  • After the events for the key have been processed, you need to put the key back into a ready state by invoking reset.

Example code 1 (use thread)

Example code 2 (use loop)

Output

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">