Monitor subfolders with a Java watch service

后端 未结 3 2141
小蘑菇
小蘑菇 2020-12-06 01:44

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

Path _directotyToWatch = Paths.get(\"E:/Raja\");
WatchService watcherSvc         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 02:28

    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() {
    
            @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.java.

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

提交回复
热议问题