Java:nio WatchService - 无法检测第二个文件的创建。为什么?
我正在尝试检测文件夹中的文件创建,但 WatchService 无法检测第二个文件创建。它停留在 key = watcher.take() 处。知道为什么吗?我使用的是 Ubuntu 11.04 x86。
private void watchWorkingDirectory() {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key;
key = Paths.get(tailSource, "").register(watcher, ENTRY_CREATE);
for (;;) {
System.err.println("Watching current working directory...............................................");
// wait for key to be signalled
key = watcher.take();
System.out.println("Event detected:");
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == ENTRY_CREATE) {
tailSource = event.context().toString();
System.out.println(tailSource);
File file = new File(tailSource);
BufferedReader br = new BufferedReader(new FileReader(file));
System.out.println(br.readLine());
tailer = new Tailer(file, tListener, 1, false);
(new Thread(tailer)).start();
}
}
}
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
i am trying to detect file creation in a folder but WatchService
can't detect second file creation. it stucks at key = watcher.take()
. Any idea why? I am using Ubuntu 11.04 x86.
private void watchWorkingDirectory() {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key;
key = Paths.get(tailSource, "").register(watcher, ENTRY_CREATE);
for (;;) {
System.err.println("Watching current working directory...............................................");
// wait for key to be signalled
key = watcher.take();
System.out.println("Event detected:");
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == ENTRY_CREATE) {
tailSource = event.context().toString();
System.out.println(tailSource);
File file = new File(tailSource);
BufferedReader br = new BufferedReader(new FileReader(file));
System.out.println(br.readLine());
tailer = new Tailer(file, tListener, 1, false);
(new Thread(tailer)).start();
}
}
}
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在处理事件后调用 key.reset() 。
http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes
You have to invoke key.reset() after processing events.
http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes