且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何查看文件夹和子文件夹的更改

更新时间:2022-11-28 19:11:45

WatchService仅监视您注册的Path.它不会递归地通过这些路径.

A WatchService only watches the Paths you register. It does not go through those paths recursively.

给出/Root作为注册路径

/Root
    /Folder1
    /Folder2
        /Folder3

如果Folder3中有更改,它将无法捕获.

If there is a change in Folder3, it won't catch it.

您可以自己用递归方式注册目录路径

You can register the directory paths recursively yourself with

private void registerRecursive(final Path root) throws IOException {
    // register all subfolders
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
            return FileVisitResult.CONTINUE;
        }
    });
}

现在,WatchService将通知Path root的所有子文件夹中的所有更改,即.您传递的Path参数.

Now the WatchService will notify all changes in all subfolders of Path root, ie. the Path argument you pass.