我有一个程序,该程序使用 WatchService
观察文件更新目录。修改文件时,我会得到事件。但是,我注意到,即使我在VI中打开文件,并且不修改其内容,也会调用Watch Service poll
方法。我的代码如下:
watcher = FileSystems.getDefault().newWatchService();
Path path = Paths.get("conf");
path.register(watcher, ENTRY_MODIFY);
WatchKey key = null;
key = watcher.poll(MAX_WAIT_TIME, TimeUnit.SECONDS);
if (key != null) {
for (WatchEvent<?> events : key.pollEvents()) {
WatchEvent<Path> ev = cast(events);
Path fileName = ev.context();
}
在上面的代码中,watch.poll等待 MAX_WAIT_TIME
进行 ENTRY_MODIFY
事件。但是,当我在要观看的目录中打开文件时,并在不更改内容的情况下关闭... watcher.poll
接收事件并停止等待。是否需要设置一些参数,我缺少?
如果在关闭之前保存文件,则操作系统即使没有更改,也会将文件视为修改,并且这些将触发entry_modify事件。另外,您的代码仅采用一个手表键。如果您想继续观看目录,则需要将Watcher.poll指令放入循环。
我在Java7中尝试了以下代码,并且在Windows中对我来说很好。
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.nio.file.StandardWatchEventKinds;
public class WatchServiceJava7Feature {
public static void main(String[] args) throws Exception {
System.out.println("here ");
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path= Paths.get("C:\User\code\watchservice\");
System.out.println("here 1");
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
while(true)
{
WatchKey key = watchService.take(); // this will return the keys
for(WatchEvent<?> event : key.pollEvents())
{
WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
WatchEvent.Kind<Path> kind = watchEvent.kind();
switch(kind.name()) {
case "ENTRY_MODIFY":
System.out.println("Case Modify :Event on "+ event.context().toString() + " is "+ kind);
break;
case "ENTRY_DELETE":
System.out.println("Case Delete :Event on "+ event.context().toString() + " is "+ kind);
break;
case "ENTRY_CREATE":
System.out.println("Case Create :Event on "+ event.context().toString() + " is "+ kind);
break;
}
}
key.reset();
}
}
}