我可以使用WatchService(而不是整个目录)查看单个文件更改吗? [英] Can I watch for single file change with WatchService (not the whole directory)?

查看:110
本文介绍了我可以使用WatchService(而不是整个目录)查看单个文件更改吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试注册文件而不是目录抛出java.nio.file.NotDirectoryException 时。我可以监听单个文件更改,而不是整个目录吗?

When I'm trying to register a file instead of a directory java.nio.file.NotDirectoryException is thrown. Can I listen for a single file change, not the whole directory?

推荐答案

只需过滤所需文件的事件即可目录:

Just filter the events for the file you want in the directory:

final Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop");
System.out.println(path);
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
    final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
    while (true) {
        final WatchKey wk = watchService.take();
        for (WatchEvent<?> event : wk.pollEvents()) {
            //we only register "ENTRY_MODIFY" so the context is always a Path.
            final Path changed = (Path) event.context();
            System.out.println(changed);
            if (changed.endsWith("myFile.txt")) {
                System.out.println("My file has changed");
            }
        }
        // reset the key
        boolean valid = wk.reset();
        if (!valid) {
            System.out.println("Key has been unregisterede");
        }
    }
}

这里我们检查一下是否有变化文件是myFile.txt,如果它然后做任何事情。

Here we check whether the changed file is "myFile.txt", if it is then do whatever.

这篇关于我可以使用WatchService(而不是整个目录)查看单个文件更改吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆