2013-04-08 108 views

回答

2

此代碼觀看目錄文件添加,刪除或修改:

Path testDirectory = Files.createTempDirectory(getClass().getName()); 
WatchService watcher = FileSystems.getDefault().newWatchService(); 
testDirectory.register(watcher, 
    StandardWatchEventKinds.ENTRY_CREATE, 
    StandardWatchEventKinds.ENTRY_MODIFY, 
    StandardWatchEventKinds.ENTRY_DELETE); 
for(;;) { 
    WatchKey key = watcher.take(); 
    log("key = watcher.take()"); 
    if(key.isValid()) { 
     log("key.isValid()"); 
     List< WatchEvent<?>> lst = key.pollEvents(); 
     for(WatchEvent<?> e : lst) { 
     log("WatchEvent polled: " + e.kind() + ": " + e.context()); 
     if(e.kind() == StandardWatchEventKinds.ENTRY_CREATE) { 
      Path path = (Path)e.context(); 
      File file = path.toFile(); 
      addFile(new File(testDirectory.toFile(), file.getPath())); 
     } 
     else if(e.kind() == StandardWatchEventKinds.ENTRY_DELETE) { 
      Path path = (Path)e.context(); 
      File file = path.toFile(); 
      removeFile(new File(testDirectory.toFile(), file.getPath())); 
     } 
     } 
     key.reset(); 
    } 
} 

參與這個代碼中的類:

This part of the io tutorial顯示更多並解釋此API的動機。

0

This是所需的Java教程。 java.nio.file包提供了一個文件更改通知API,稱爲Watch Service API。該API使您能夠使用監視服務註冊一個或多個目錄。註冊時,您告訴服務您感興趣的事件類型:文件創建,文件刪除或文件修改

更多關於它here

+0

我不想讓那個觀察者不是一個目錄或一些目錄列表。我想要一個整個系統的清單工作,無論粘貼工作在哪裏進行。 – 2013-04-08 18:46:24