Monitor subfolders with a Java watch service

淺唱寂寞╮ 提交于 2019-11-27 22:59:00

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

    });

}

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

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.

The reason you are only seeing an event for "E:/Raja/Test" and not "E:/Raja/Test/Foo.txt" (for example) is that you've only registered the "E:/Raja" directory with the service. This means you will see events on the directory and its immediate members. The "E:/Raja/Test" is a member of the directory, and you are getting events to say that is has been changed ... when files are added to it.

The solution is to register all of subdirectories of "E:/Raja" as well ... going as far down the directory hierarchy as you need to go.

Nick

I know this is ugly, hopefully somebody has a better answer but you can create a list of every file in every subfolder and there last modified times.

When you receive ENTRY_CREATE or ENTRY_DELETE compare the folder to your list to figure out which file was changed

When you receive a ENTRY_MODIFY compare the last modified times.

Remember to update your list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!