2012-05-24 67 views
2

我可以做多少個newWatchService?我可以在Java 7中創建多少個newWatchService?

try{ 
    for(Path path : PathList) { 
     watcher = path.getFileSystem().newWatchService(); 
    } catch (IOException e) { 
     log.error(e); 
    } 
} 

- >結果:IOExeption:打開太多的文件...

+0

雖然我還沒有嘗試過手錶的服務,你一次只能得到這麼多的文件描述符。你有多少錯誤?另外請記住,監視服務正在輪詢文件系統,因此在某些時候您可以爲系統提供大量的IO工作。 –

回答

0

我想你應該只創建一個觀察者的服務,但註冊[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); 
相關問題