簡體   English   中英

獲取使用WatchService創建的文件的位置

[英]Get location of file created using WatchService

我正在使用WatchService來監視文件夾及其子文件夾中創建的新文件。 但是,在創建文件時,WatchService會提供所創建文件的名稱,而不是其位置。 有沒有一種方法可以獲取所創建文件的絕對/相對路徑。

解決此問題的一種粗略方法是在所有子文件夾中搜索文件名,然后找到具有最新創建日期的文件名。 有一個更好的方法嗎?

如果在dir目錄中注冊WatchService ,則獲取完整路徑的時間很簡單:

// 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
      }
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM