0

示例:我的桌面有一个子文件夹“Desktop/sub”

如果只注册了 Desktop 并且一旦启动 WatchService 我修改子文件夹的内容..它是否应该触发 ENTRY_MODIFY?我试过了,但没有。它仅适用于修改注册文件夹中的文件(在本例中为桌面)。

只是问这个问题,因为在 OCPJP7 的模拟考试中,它说实际上即使修改诸如“Desktop/sub”之类的子文件夹,例如在“Desktop/sub”中删除一个文件,它也应该触发该事件。

但是,我再次尝试了它,但它不起作用。

这是代码:

WatchKey key = ws.poll(5, TimeUnit.SECONDS);

if (key ==null)
{
    continue;
}
List<WatchEvent<?>> lista = key.pollEvents();

for (WatchEvent<?> event : lista)
{
    switch(event.kind().toString())
    {
    case "ENTRY_CREATE": System.out.println("There has been a creation over here: "+event.context());break;
    case "ENTRY_MODIFY": System.out.println("There has been a modification over here: "+event.context());break;
    case "ENTRY_DELETE": System.out.println("There has been a deletion over here: "+event.context());

    }

    key.reset();
}

提前致谢。

4

1 回答 1

0

WatchService仅查看已注册 s 中的文件和文件夹修改Path

如果您注册了

WatchService service = FileSystems.getDefault().newWatchService();
Path path = Paths.get("/Desktop");
path.register(service, StandardWatchEventKinds.ENTRY_MODIFY);

然后Desktop将看到添加一个文件夹。Desktop将看到更改文件。添加一个文件夹Desktop/Subs也会看到,因为Subs里面的文件夹Desktop被修改了。但是,Desktop/Subs不会看到修改文件,因为该路径未向服务注册。

您始终可以Desktop递归地注册所有路径

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;
        }
    });
}

我没有在 Linux 上尝试过,但以下适用于 Windows

public static void main(String[] args) throws Exception {   

    WatchService service = FileSystems.getDefault().newWatchService();
    Path path = Paths.get("/Desktop");
    path.register(service, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_CREATE);
    WatchKey key = null;
    while(true) {
        key = service.take();

        List<WatchEvent<?>> lista = key.pollEvents();

        for (WatchEvent<?> event : lista)
        {
            switch(event.kind().toString())
            {
            case "ENTRY_CREATE": System.out.println("There has been a creation over here: "+event.context());break;
            case "ENTRY_MODIFY": System.out.println("There has been a modification over here: "+event.context());break;
            case "ENTRY_DELETE": System.out.println("There has been a deletion over here: "+event.context());

            }

            key.reset();
        }
    }
}
于 2013-09-02T13:52:57.353 回答