我想你應該只創建一個觀察者的服務,但註冊[M]任何路徑它。
根據Oracle文檔(https://docs.oracle.com/javase/tutorial/essential/io/walk.html)給出的示例,僅創建一個監視服務,作爲WatchDir類的成員變量。請注意「this.watcher」
public class WatchDir {
private final WatchService watcher;
在別處類...
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
同樣的服務用於遞歸註冊一個指定文件夾內的所有路徑。
最後,登記發生在這裏...
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
雖然我還沒有嘗試過手錶的服務,你一次只能得到這麼多的文件描述符。你有多少錯誤?另外請記住,監視服務正在輪詢文件系統,因此在某些時候您可以爲系統提供大量的IO工作。 –