使用Java监视服务监视子文件夹 [英] Monitor subfolders with a Java watch service

查看:159
本文介绍了使用Java监视服务监视子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 watchKey 来监听特定文件夹中的文件更改。

I am using watchKey to listen for a file change in a particular folder.

Path _directotyToWatch = Paths.get("E:/Raja");
WatchService watcherSvc = FileSystems.getDefault().newWatchService();
WatchKey watchKey = _directotyToWatch.register(watcherSvc, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

while (true) {
    watchKey=watcherSvc.take();
    for (WatchEvent<?> event: watchKey.pollEvents()) {
        WatchEvent<Path> watchEvent = castEvent(event);
        System.out.println(event.kind().name().toString() + " " + _directotyToWatch.resolve(watchEvent.context()));
        watchKey.reset();
    }
}



工作正常为了我。如果我修改raja文件夹中的文件,它会给我带路径的文件名。但是,当我将一些文件放在像E:/ Raja / Test这样的子文件夹中时,它只给出了我放置它的路径,而不是文件名。


It working fine for me. If I modify a file in raja folder it gives me the file name with path. But, when I put some files in subfolders like "E:/Raja/Test", it gives me only the path where I put it, not the file name.

如何获取文件名?

推荐答案

原因为什么你没有得到文件名在子文件夹中创建/修改的内容由 Stephen C 在其答案中提供。

The reason why you're not getting the file name created/modified inside a subfolder is given by Stephen C in his answer.

以下是如何注册目录子目录以观察事件的简单示例您感兴趣的是:

Here is a simple example of how to register directories and subdirectories to watch them for the events you are interested in:

/**
 * 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;
        }

    });

}






检查发布官方Java教程:观看目录以进行更改。在那里你可以找到非常好的解释和源代码示例。


Check out the official Java Tutorials: Watching a Directory for Changes. There you can find very nice explanations and examples with the source code.

特别是你会对这个如何观看目录(或目录的例子感兴趣树)用于更改文件: WatchDir

Particularly you'll be interested in this example of how to watch a directory (or directory tree) for changes to files: WatchDir.

我上面提供的方法来自这个例子(省略)一些部分为了简洁。)
阅读教程了解详情。

The method I supplied above was taken from this example (omitting some parts for brevity).
Read the tutorial for the details.

这篇关于使用Java监视服务监视子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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