Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking.I'm 23, born in Romania, student at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff. I know that I look and act differently from most developers, but this is why you will love to work with me! Constantin has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

How to watch the file system for changes in Java 7 (JDK 7)

03.17.2011
| 43143 views |
  • submit to reddit
Java 7 uses the underlying file system functionalities to watch the file system for changes. Now, we can watch for events like creation, deletion, modification, and get involved with our own actions. For accomplish this task, we need:

• An object implementing the Watchable interface - the Path class is perfect for this job.
• A set of events that we are interested in - we will use StandardWatchEventKind which implements the WatchEvent.Kind<T>.
• An event modifier that qualifies how a Watchable is registered with a WatchService.
• A watcher who watch some watchable – per example, a watcher that watches the File System for changes. The abstract class is java.nio.file.WatchService but we will be using the FileSystem object to create a watcher for the File System.

The below example follows the above scenario:
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKind;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        //define a folder root
        Path myDir = Paths.get("D:/data");       

        try {
           WatchService watcher = myDir.getFileSystem().newWatchService();
           myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE, 
           StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

           WatchKey watckKey = watcher.take();

           List<WatchEvent<?>> events = watckKey.pollEvents();
           for (WatchEvent event : events) {
                if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
                    System.out.println("Created: " + event.context().toString());
                }
                if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
                    System.out.println("Delete: " + event.context().toString());
                }
                if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
                    System.out.println("Modify: " + event.context().toString());
                }
            }
           
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }
}
The FileSystem object and the WatchService can also be created like this:
FileSystem fileSystem = FileSystems.getDefault();
WatchService watcher = fileSystem.newWatchService();
And the Path (watchable), what we watch, and register it with the WatchService object like this:
Path myDir = fileSystem.getPath("D:/data");
myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE, 
          StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);
References
Published at DZone with permission of its author, Constantin Alin. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

cowwoc replied on Thu, 2011/03/17 - 10:27am

Are you telling me we have to poll for file changes?! Isn't there a way to handle file changes asynchronously?

Ronald Miura replied on Thu, 2011/03/17 - 2:20pm in response to: cowwoc

create a polling thread :)

Amin Mansuri replied on Thu, 2011/03/17 - 4:50pm

What about cleanup? Doesn't the service need to be closed or something? Isn't there some underlyng OS resource here?

Amir Laher replied on Thu, 2011/03/17 - 5:27pm

Strange that you can't just pass a type of "event handler" to the WatchService instead of this polling technique.

It feels a bit cumbersome, and only marginally better than polling the folder 'manually'.

Annoying!

Gervais Blaise replied on Fri, 2011/03/18 - 3:05am

Damn, that realy strange. Where are the Listeners (Observers) ? I'm sure that the first thing I'm a going to do is to wrap that to have something that is more closer that Sun as done with Swing with EventListeners.

Ryan Developer replied on Fri, 2011/03/18 - 7:48am

I heard that you can't watch an entire directory tree (recursively) for changes, you can only watch the directory you specified.  In NetBeans 7 they chose not to use this feature of JDK7 and instead wrote their own code to call into OS native APIs to watch an entire directory tree.

Joerg Wassmer replied on Fri, 2011/03/18 - 8:59am

Almost useless, compared to polling the file system "manually". The only thing the new API is good for is to reduce calls to the native filesystem. All the complicated logic you still have to do for yourselves.

Alan Bateman replied on Fri, 2011/03/18 - 9:32am

The WatchService is deliberately a low-level API as it needs to serve multiple masters. A server application can use it in conjunction with a thread pool to service events concurrently for example. A client application will likely use a single thread to process events with a listener like API on top. In general it's a bit of a niche/advanced area.

Some of the comments here give the impression that it's polling the file system. That is only the case on operating systems where there isn't any operating system facility/mechanism to get events from the file system. It uses native facilities on Linux (folks will have heard of inotify), Windows, and Solaris 11 for example. The take() in the code example just blocks until it can retrieve the next signalled key (with events). Someone also asked about clean-up, and WatchService extends Closeable for that purpose.

One nit with the code fragment in the original post is that it is missing a call to the reset() method and so doesn't actually work as expected. There is working example in the JDK sample directory if anyone needs it. The example can be used to watch a directory for changes or a file tree. Watching a file tree can be a bit awkward as it's not something that most operating systems support. The API is designed to allow for this (and other) features to be added in the future. At this time, I think Windows is the only operating system that we've encountered that has a native facillity to watch file tree.

 

Liezel Jane Jandayan replied on Tue, 2011/08/23 - 10:53pm

You just register to be notified about and wait to get your notifications. The best part of it is, you can assign as much listeners as you like and even from different threads, with no code,it is all thread safe.-Jonathan Berkowitz

Steave Lee replied on Thu, 2013/09/19 - 2:39am

 Java 7 uses the underlying file system functionalities to watch the file system for changes. Now, we can watch for events like creation, deletion.....

______________

pallet racking

Shrenik Vadhar replied on Tue, 2013/09/24 - 5:25am

 I downloaded JDK 7-EA and Netbeans 7 (Eclipse doesn't support Java 7 language changes yet) and looked for interesting changes in the release...

Ref: mono flange valve

_____________

mono flange valve 

John Thomas replied on Thu, 2013/09/26 - 3:22am

File Change Notification is a new feature added in JDK 7. It is a part of the new file system API (NIO 2.0).
Ref: hrms mumbai
_________________
hrms mumbai

Ju Peter replied on Fri, 2013/09/27 - 7:07am

We are using jdk 7to tracking the file create in my system. And Up till now all thing are work ok. Every file is created on my system tracked by my program.

But we have trouble that when we use NFS (the directory we track actually existed on another computer in LAN).

Ref :humidity calibrator

_______________

humidity calibrator

Raok Thomas replied on Mon, 2013/09/30 - 6:12am

 The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service.

Ref :copper braided

________________

copper braided

Nimi Malho replied on Tue, 2013/10/08 - 6:05am

Closing a file system causes all open channels, watch services, and other ... The file hierarchies may change during the lifetime of the Java virtual machine.

Ref: party service singapore

_______________

party service singapore 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.