gpt4 book ai didi

java - 捕获目录内发生的事件

转载 作者:行者123 更新时间:2023-11-29 07:06:03 24 4
gpt4 key购买 nike

我通过以下方法使用 Java 7 nio WatchService 观看目录。

Path myDir = Paths.get("/rootDir");

try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

WatchKey watckKey = watcher.take();

List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
JOptionPane.showMessageDialog(null,"Created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
JOptionPane.showMessageDialog(null,"Delete: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
JOptionPane.showMessageDialog(null,"Modify: " + event.context().toString());
}
}

} catch (Exception e) {
System.out.println("Error: " + e.toString());
}

但是上面的方法只响应目录中发生的一个事件,之后 watcher 不响应该文件夹中发生的事件。有没有一种方法可以修改它以捕获文件夹内发生的所有事件。我也想修改它以捕获子文件夹中发生的事件。有人可以帮助我吗。

谢谢。

最佳答案

来自 the JavaDoc of WatchService :

A Watchable object is registered with a watch service by invoking its register method, returning a WatchKey to represent the registration. When an event for an object is detected the key is signalled, and if not currently signalled, it is queued to the watch service so that it can be retrieved by consumers that invoke the poll or take methods to retrieve keys and process events. Once the events have been processed the consumer invokes the key's reset method to reset the key which allows the key to be signalled and re-queued with further events.

您只调用了 watcher.take()一次。

要查看更多事件,您必须调用 watchKey.reset()在使用了 WatchEvent 之后。将所有这些放在一个循环中。

while (true) {
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
// process event
}
watchKey.reset();
}

另请查看 the relevant section of the Java Tutorial .

关于java - 捕获目录内发生的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19678170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com