如何使用WatchService观看多个目录?

问题描述 投票:0回答:2

不明白,怎么办

watcher.take();

知道要举报哪个目录?它是否报告其注册的每个目录?

dir.register(watcher...

如果我有多个观察者,他们是否只会报告针对他们注册的那些目录?

register()的返回值的用途是什么?看起来这里的描述中从未使用过它:http://docs.oracle.com/javase/tutorial/essential/io/notification.html

java nio watchservice
2个回答
2
投票

您使用

Path
register
位于
Path
WatchService
的文件。

如果发生事件,它将在

WatchService
中排队,您可以使用
take()
检索它。
take()
不知道实际的
Path

是的,

WatchService
只会报告已注册的
Path
的事件。

您可以使用

WatchKey
方法返回的
register
WatchKey
返回的
take()
进行比较。显然,您还可以执行 javadoc 中描述的所有操作。


0
投票

我们需要递归注册文件夹 F1 及其所有子文件夹 F11 和 F12。 官方文档本身也提供了解决方案。

这是您需要递归文件夹 F1 及其所有子文件夹到 watchService 的代码段:

/**
 * Register the given directory and all its sub-directories with the WatchService.
 */
private void registerAll(final Path start) throws IOException {
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
            return FileVisitResult.CONTINUE;
        }

    });

}

如果有更多细节或者您不明白该代码段的用法。参考官方文档。下面提供了链接。

官方文档参考:
https://docs.oracle.com/javase/tutorial/essential/io/notification.html https://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

© www.soinside.com 2019 - 2024. All rights reserved.