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

点点圈 提交于 2019-11-30 09:06:53
patrickmdnet

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

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