2017-04-25 56 views
1

我需要監控多個文件夾,我想知道哪個文件夾已經收到 事件來執行特定的處理。我試過這段代碼。Java監控多個文件夾

WatchService watchService = FileSystems.getDefault().newWatchService(); 
opexFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); 
docupostFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); 

    boolean valid = true; 
    do { 
     WatchKey watchKey = watchService.take(); 
     for (WatchEvent<?> event : watchKey.pollEvents()) { 
      WatchEvent.Kind kind = event.kind();     
      if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {      
       String fileName = event.context().toString();     

       //here I want to khow the path of the folder that has 
       // received the ENTRY event 
       String pathToExplore = ??; 
       if (pathToExplore has some value) { 
       treatments; 
       } else { 
       other treatments; 
       } 

      } 
     } 
     valid = watchKey.reset(); 

    } while (valid); 
} 

是否有可能做到這一點,或者我必須爲每個文件夾創建watchService。

謝謝。

回答

1

WatchService.take()將爲每個觀看目錄返回不同的觀看鍵。您可以從WatchKey::watchable()方法中獲得觀看的目錄。

所以通過檢查返回的值WatchKey::watchable()你會知道這個事件是哪個目錄。


是在WatchKey usualy不變?

不可以WatchKey不是常數。您通過致電WatchKey watchKey = watchService.take();獲得它您已經在您發佈的代碼中完成了它。

我怎麼能說這是opexFolder的關鍵或docupostFolder的關鍵

只需撥打Path directory = WatchKey::watchable()

下面是一個簡單的示例應用程序:從樣品應用

import java.io.IOException; 
import java.nio.file.*; 
import java.nio.file.attribute.BasicFileAttributes; 

public final class WatchServiceExample { 

    public static void main(String[] args) throws Exception { 
     //We'll use this watch service to monitor all directories we are interested in 
     final WatchService watchService = FileSystems.getDefault().newWatchService(); 

     //We'll use this directory for the test in order not to create junk in the system 
     final Path tempDirectory = Files.createTempDirectory("watch-service-example"); 
     System.out.println("Created temporary directory: " + tempDirectory.toAbsolutePath()); 

     for (int i = 0; i < 10; i++) { 
      final Path watchedDir = Files.createDirectory(tempDirectory.resolve("watched_" + i)); 
      System.out.println("Created watched directory: " + watchedDir.toAbsolutePath()); 
      watchedDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); 
     } 

     System.out.println("Initialization complete. When you create an entry in the watch dirs you'll be notified."); 
     while (true) { 
      final WatchKey watchKey = watchService.take(); 
      final Watchable watchable = watchKey.watchable(); 

      //Since we are registering only paths in teh watch service, the watchables must be paths 
      if (!(watchable instanceof Path)) { 
       throw new AssertionError("The watchable should have been a Path"); 
      } 

      final Path directory = (Path) watchable; 
      System.out.println("Processing events for watched directory: " + directory); 

      for (WatchEvent<?> event : watchKey.pollEvents()) { 
       System.out.println("Received event '" 
        + event.kind() 
        + "' for entry '" 
        + event.context() 
        + "' in watched directory '" 
        + directory + "'" 
       ); 
      } 

      if (!watchKey.reset()) { 
       System.out.println("Failed to reset watch key: will not process more events"); 
       break; 
      } 
     } 

     //Lets clean up after ourselves 
     Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() { 
      @Override 
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 
       Files.delete(file); 
       return FileVisitResult.CONTINUE; 
      } 

      @Override 
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { 
       Files.delete(dir); 
       return FileVisitResult.CONTINUE; 
      } 
     }); 
    } 
} 

輸出:

Created temporary directory: /tmp/watch-service-example4292865635932187600 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_0 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_1 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_2 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_3 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_4 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_5 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_6 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_7 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_8 
Created watched directory: /tmp/watch-service-example4292865635932187600/watched_9 
Initialization complete. When you create an entry in the watch dirs you'll be notified. 
Processing events for watched directory: /tmp/watch-service-example4292865635932187600/watched_5 
Received event 'ENTRY_CREATE' for entry 'test' in watched directory '/tmp/watch-service-example4292865635932187600/watched_5' 
Processing events for watched directory: /tmp/watch-service-example4292865635932187600/watched_8 
Received event 'ENTRY_CREATE' for entry 'test' in watched directory '/tmp/watch-service-example4292865635932187600/watched_8' 
+0

WatchKey通常不變嗎?我怎麼能說這是opexFolder的key或docupostFolder的關鍵? –

+0

@ M.MELKI我已經更新我的答案 –

+0

非常感謝! –