2017-10-12 134 views
2

我試圖監視更改的文件夾。此文件夾包含我不想看的子文件夾。不幸的是,WatchService通知這些子文件夾的改變了我。我想這是因爲這些文件夾更新的最後更改日期。WatchService排除的文件夾

於是,我就exlude他們:

WatchService service = FileSystems.getDefault().newWatchService(); 
workPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, 
      StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); 
try { 
    WatchKey watchKey = watchService.take(); 
    for (WatchEvent<?> event : watchKey.pollEvents()) { 
     @SuppressWarnings("unchecked") 
     WatchEvent<Path> ev = (WatchEvent<Path>) event; 
     Path fileName = ev.context(); 
     if (!Files.isDirectory(fileName)) { 
      logger.log(LogLevel.DEBUG, this.getClass().getSimpleName(), 
        "Change registered in " + fileName + " directory. Checking configurations."); 
      /* do stuff */ 
     } 
    } 
    if (!watchKey.reset()) { 
     break; 
    } 
} catch (InterruptedException e) { 
    return; 
} 

這不工作,雖然。上下文的結果路徑是相對的,並且Files.isDirectory()無法確定它是目錄還是文件。

有沒有辦法排除子文件夾?

回答

2

你可以嘗試下面的代碼片段。爲了獲得完整路徑,您需要調用resolve()函數

Map<WatchKey, Path> keys = new HashMap<>(); 

    try { 
     Path path = Paths.get("<directory u want to watch>"); 
     FileSystem fileSystem = path.getFileSystem(); 
     WatchService service = fileSystem.newWatchService(); 

     Files.walkFileTree(path, new SimpleFileVisitor<Path>() { 
       @Override 
       public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { 
        if (<directory you want to exclude>) { 
          return FileVisitResult.SKIP_SUBTREE; 
        } 

        WatchKey key = dir.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); 
        keys.put(key, dir); 
        return FileVisitResult.CONTINUE; 
       } 
     }); 

     WatchKey key = null; 
     while (true) { 
      key = service.take(); 
      while (key != null) { 
       WatchEvent.Kind<?> kind; 
       for (WatchEvent<?> watchEvent : key.pollEvents()) { 
        kind = watchEvent.kind(); 
        if (OVERFLOW == kind) { 
         continue; 
        } 

        Path filePath = ((WatchEvent<Path>) watchEvent).context(); 
        Path absolutePath = keys.get(key).resolve(filePath); 

        if (kind == ENTRY_CREATE) { 
         if (Files.isDirectory(absolutePath, LinkOption.NOFOLLOW_LINKS)) { 
          WatchKey newDirKey = absolutePath.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); 
          keys.put(newDirKey, absolutePath); 
         } 
        } 

       } 
       if (!key.reset()) { 
        break; // loop 
       } 
      } 
     } 
    } catch (Exception ex) { 
    } 
+0

謝謝。解決幫助。 'Path fileName = workPath.resolve(ev.context())' –