java 7 feature – java watchservice-hello world


java7 introduce a new feature called WatchService. You can now register particular directory in the file system and can trigger any member function based on the event it occurs.

Before the WatchService feature, you need to create a thread continuously watch the file system, and you need to check the last modified time stamp
to get to know what really changed, and maintains the updated files is cumbersome. This will be a boost to lot of file system based operations.

Here is a sample hello world demo demonstrate the File system watch service.

package com.ananth.java7

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.*;

public class JavaWatchServiceDemo {
	private Path path = null;
	private WatchService watchService = null;

	private void initialize() {
		path = Paths.get("/home/ananth/test");  // get the directory which needs to be watched.
		try {
			watchService = FileSystems.getDefault().newWatchService();
			path.register(watchService, ENTRY_CREATE, ENTRY_DELETE,
					ENTRY_MODIFY);   // register the watch service on the path. ENTRY_CREATE-register file create event, ENTRY_DELETE=register the delete event, ENTRY_MODIFY- register the file modified event
		} catch (IOException e) {
			System.out.println("IOException"+ e.getMessage());
		}
	}
/**
 * Once it added to the watch list it will start to monitor the changes on the directory 
 */
	private void doMonitor() {
		WatchKey key = null;
		while(true) {  // important - create an indefinite loop to watch the file system changes.
			try {
				key = watchService.take();
				for (WatchEvent event : key.pollEvents()) {
					Kind kind = event.kind();
					System.out.println("Event on " + event.context().toString() + " is " + kind);
				}
			} catch (InterruptedException e) {
				System.out.println("InterruptedException: "+e.getMessage());
			}
			boolean reset = key.reset();
			if(!reset)
				break;
		}
	}

	public static void main(String[] args) {
		JavaWatchServiceDemo watchservicedemo = new JavaWatchServiceDemo();
		watchservicedemo.initialize();
		watchservicedemo.doMonitor();
	}
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s