Thursday, February 6, 2014

Java - Watch

import static java.nio.file.StandardWatchEventKinds.*;

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.WatchKey;
import java.nio.file.WatchService;
import java.util.Date;
import java.util.List;

class DirWatcherThread extends Thread {
String dirPath;

public DirWatcherThread(String dirPath) {
this.dirPath = dirPath;
}

public void run() {
System.out.println("Directory Watcher is started");

dirWatcher();

System.out.println("Directory Watcher is ended");
}

public void dirWatcher() {
try {
Path dirP = Paths.get(dirPath);
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key;

dirP.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

for (int i = 0; i < 4; i++) {
key = watcher.take();

String watchedTime = new Date().toString();
List<WatchEvent<?>> eventList = key.pollEvents();

for (WatchEvent<?> event : eventList) {
Path name = (Path) event.context();

if (event.kind() == ENTRY_CREATE) {
System.out.println(name + " is created at "
+ watchedTime);
} else if (event.kind() == ENTRY_DELETE) {
System.out.println(name + " is deleted at "
+ watchedTime);
} else if (event.kind() == ENTRY_MODIFY) {
System.out.println(name + " is modified at "
+ watchedTime);
}
}

key.reset();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public class Test {

public static void main(String[] args) {
DirWatcherThread dirWT = new DirWatcherThread("D:\\Test");
dirWT.start();
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.