Tuesday, July 3, 2012

Directory Change Listener Example


jdk 7 Watch Service Sample Usage
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. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.



import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;


public class DirListener {


public static void main(final String[] args) {
try {
Runnable r = new Runnable() {
@Override
public void run() {
while (true) {
handleDirectoryChangeEvent(args[0]);
}
}
};


Thread t = new Thread(r);
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}


private static void handleDirectoryChangeEvent(String path) {
try {
Path dir = Paths.get(path);
WatchService watchService = FileSystems.getDefault().newWatchService();
dir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY);
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path name = ev.context();
Path child = dir.resolve(name);
System.out.format("%s: %s\n", event.kind().name(), child);
}
        } catch (Exception x) {
            return;
        }
}
}



program output...



ENTRY_CREATE: /home/ssunel/jars/reloadtes1.jar
ENTRY_CREATE: /home/ssunel/jars/reloadtest.jar
ENTRY_CREATE: /home/ssunel/jars/zi3iCChW
ENTRY_CREATE: /home/ssunel/jars/Untitled Document
ENTRY_CREATE: /home/ssunel/jars/ss.txt
ENTRY_CREATE: /home/ssunel/jars/.goutputstream-RVZAHW
ENTRY_MODIFY: /home/ssunel/jars/.goutputstream-RVZAHW
ENTRY_MODIFY: /home/ssunel/jars/.goutputstream-RVZAHW
ENTRY_CREATE: /home/ssunel/jars/ss.txt~
ENTRY_MODIFY: /home/ssunel/jars/reload.jar



1 comment: