获取使用WatchService创建的文件的位置

时间:2018-01-03 18:49:49

标签: java watchservice

我正在使用WatchService来查看创建的新文件的文件夹及其子文件夹。但是,在创建文件时,WatchService会提供创建的文件的名称,而不是其位置。有没有办法获得创建的文件的绝对/相对路径。

解决此问题的一种粗略方法是在所有子文件夹中搜索文件名,并找到具有最新创建日期的文件名。有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

如果在WatchService目录上注册dir,何时获取完整路径很简单:

// If the filename is "test" and the directory is "foo",
// the resolved name is "test/foo".
Path path = dir.resolve(filename);

它有效,因为WatchService只监视一个目录。如果要监视子文件夹,则必须注册新的WatchServices

回答您的无格式评论(这可以解决您的问题)

public static void registerRecursive(Path root,WatchService watchService) throws IOException { 
   WatchServiceWrapper wsWrapper = new WatchServiceWrapper();

   // register all subfolders 
   Files.walkFileTree(root, new SimpleFileVisitor<Path>() { 
      public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
         wsWrapper.register(watchService, dir);
         return FileVisitResult.CONTINUE; 
      } 
   });  

   wsWrapper.processEvents();
}

public class WatchServiceWrapper {
   private final Map<WatchKey,Path> keys;

   public WatchServiceWrapper () {
      keys = new HashMap<>();
   }

   public void register(WatchService watcher, Path dir) throws IOException {
      WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
      keys.put(key, dir);
   }

   public void processEvents() {
      for (;;) {
        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        //get fileName from WatchEvent ev (code emitted)
        Path fileName = ev.context();

        Path fullFilePath = dir.resolve(fileName);

        //do some other stuff
      }
   }
}
相关问题