我正在尝试来自Pro Java 7 NIO.2 第 118 页的小程序
代码是:
class WatchRafaelNadal {
public void watchRNDir(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.take();
//get list of pending events for the watch key
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
//print it out
System.out.println(kind + " -> " + filename);
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, for example)
if (!valid) {
break;
}
}
}
}
}
public class Main {
public static void main(String[] args) {
final Path path = Paths.get("C:/Java");
WatchRafaelNadal watch = new WatchRafaelNadal();
try {
watch.watchRNDir(path);
} catch (IOException | InterruptedException ex) {
System.err.println(ex);
}
}
}
但是,当我更改global.properties
文件夹中存在的(或任何文件)中的一行时,C:\\Java
我得到的输出为 -
ENTRY_MODIFY -> global.properties
ENTRY_MODIFY -> global.properties
为什么会引发 2 次事件?
Java中是否有任何服务可以检测文件中精确修改的行/行?
JDK:jdk1.7.0_09
IDE:Eclipse Java EE IDE 版本:Juno 发布
平台:Windows 7