今天,我开始尝试一些新功能,我们在Java 7。首先是该文件的系统WatchService让我们听没有汇集到一个目录中的变化。看起来真的很棒。你刚才注册将有关更改的通知,并等待得到您的通知。它的最好的部分是,你可以指定你想尽可能多的听众,从不同的线程,即使没有代码的变化,它是所有线程安全的。下面是我做了什么,以获取有关文件被修改/删除/添加到我的非常重要的TEMP目录的通知:public class PathTest {
private static void listenForChanges(File file) throws IOException {
Path path = file.toPath();
if (file.isDirectory()) {
WatchService ws = path.getFileSystem().newWatchService();
path.register(ws, StandardWatchEventKind.ENTRY_CREATE,
StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);
WatchKey watch = null;
while (true) {
System.out.println("Watching directory: " + file.getPath());
try {
watch = ws.take();
} catch (InterruptedException ex) {
System.err.println("Interrupted");
}
List<WatchEvent<?>> events = watch.pollEvents();
watch.reset();
for (WatchEvent<?> event : events) {
Kind<Path> kind = (Kind<Path>) event.kind();
Path context = (Path) event.context();
if (kind.equals(StandardWatchEventKind.OVERFLOW)) {
System.out.println("OVERFLOW");
} else if (kind.equals(StandardWatchEventKind.ENTRY_CREATE)) {
System.out.println("Created: " + context.getFileName());
} else if (kind.equals(StandardWatchEventKind.ENTRY_DELETE)) {
System.out.println("Deleted: " + context.getFileName());
} else if (kind.equals(StandardWatchEventKind.ENTRY_MODIFY)) {
System.out.println("Modified: " + context.getFileName());
}
}
}
} else {
System.err.println("Not a directory. Will exit.");
}
}
public static void main(String[] args) {
if (args.length > 0) {
File file = new File(args[0]);
try {
System.out.println("Listening on: " + file);
listenForChanges(file);
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
System.out.println("Pass directory path as parameter");
}
}
}
是一个棘手的事情,当使用WatchService。你要记住,重置后,你调查事件的WatchKey,否则将停止更新(只有第一个目录的变化将执行你的代码,其余部分将不会做任何事情)。