File change notification example with Watch Service API - Mar Java Mit Java

File change notification example with Watch Service API

Java 7 adds a new feature for its NIO package called Watch Service API which allows applications monitoring directories and files for change events such as creation, deletion and modification. The Watch Service API is fairly simple to use, and relieves programmers from using third party libraries for files change monitoring.

So this is the simple code which monitors a directory for file additions, file deletions and file modifications

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
 
public class WatcherExample {
	public static void main(String[] args) throws Exception {
 
		WatchService watcher = FileSystems.getDefault().newWatchService();
		Path dir = Paths.get("c://downloads/watcher");
		dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
				StandardWatchEventKinds.ENTRY_DELETE,
				StandardWatchEventKinds.ENTRY_MODIFY);
		while (true) {
			WatchKey key = null;
			key = watcher.take();
			List<WatchEvent<?>> events = key.pollEvents();
			for(WatchEvent<?> event : events){
				Path p = ((WatchEvent<Path>)event).context();
				Kind<?> kind = event.kind();
				if(kind == StandardWatchEventKinds.ENTRY_CREATE){
					System.out.println("New file created - " + p);
				}
				else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
					System.out.println("File deleted - " + p);
				}
				else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
					System.out.println("File modified - " + p);
				}
			}
		}
 
	}
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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