开发者

How can I watch subdirectory for changes with WatchService? (Java)

I want to watch some directory for changes and her subdirectories. I tried to do thi开发者_如何学Cs with WatchService but I can't know from which directory the file was changed. How can I retrieve the full path from the WatchEvent?


Generally you provide the directory name of the file when starting the watchservice. Here is a tutorial demonstrating how that works:

http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes

From the tutorial:

   Path dir = ...;
   try {
       WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
   }[.....]

when you catch a notification:

   //The filename is the context of the event.
   WatchEvent<Path> ev = (WatchEvent<Path>)event;
   Path filename = ev.context();

   Path child = dir.resolve(filename);


For users who use Spring:

With Spring 4.2 WatchServiceDirectoryScanner is introduced. Now it can also catch sub directory changes.

For more information, Javadocs on WatchServiceDirectoryScanner

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜