监视服务不包括文件夹



我正在尝试监视文件夹的更改。此文件夹包含我不想观看的子文件夹。不幸的是,监视服务通知我这些子文件夹中的更改。我想发生这种情况是因为这些文件夹的最后更改日期更新。

所以我试图消除它们:

WatchService service = FileSystems.getDefault().newWatchService();
workPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
try {
    WatchKey watchKey = watchService.take();
    for (WatchEvent<?> event : watchKey.pollEvents()) {
        @SuppressWarnings("unchecked")
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path fileName = ev.context();
        if (!Files.isDirectory(fileName)) {
            logger.log(LogLevel.DEBUG, this.getClass().getSimpleName(),
                    "Change registered in " + fileName + " directory. Checking configurations.");
            /* do stuff */
        }
    }
    if (!watchKey.reset()) {
        break;
    }
} catch (InterruptedException e) {
    return;
}

不过这行不通。上下文的结果路径是相对的,Files.isDirectory()无法确定它是目录还是文件。

有没有办法排除子文件夹?

您可以尝试以下代码片段。为了获得完整路径,你需要调用 resolve() 函数

Map<WatchKey, Path> keys = new HashMap<>();
    try {
        Path path = Paths.get("<directory u want to watch>");
        FileSystem fileSystem = path.getFileSystem();
        WatchService service = fileSystem.newWatchService();
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    if (<directory you want to exclude>) {
                            return FileVisitResult.SKIP_SUBTREE;
                    }
                    WatchKey key = dir.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
                    keys.put(key, dir);
                    return FileVisitResult.CONTINUE;
                }
        });
        WatchKey key = null;
        while (true) {
            key = service.take();
            while (key != null) {
                WatchEvent.Kind<?> kind;
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    kind = watchEvent.kind();
                    if (OVERFLOW == kind) {
                        continue;
                    }
                    Path filePath = ((WatchEvent<Path>) watchEvent).context();
                    Path absolutePath = keys.get(key).resolve(filePath);
                    if (kind == ENTRY_CREATE) {
                        if (Files.isDirectory(absolutePath, LinkOption.NOFOLLOW_LINKS)) {
                            WatchKey newDirKey = absolutePath.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
                            keys.put(newDirKey, absolutePath);
                        }
                    }
                }
                if (!key.reset()) {
                    break; // loop
                }
            }
        }
    } catch (Exception ex) {
    }

相关内容

  • 没有找到相关文章

最新更新