簡體   English   中英

Java watchservice,如何找到創建文件的目錄?

[英]Java watchservice, how to find the directory where the file was created?

我正在嘗試使用Java Watchservice(NIO)來監視多個目錄,我可以在所有目錄中看到create事件,但是無法追溯到創建文件的目錄。

例如,每當創建一個新文件時,我只能看到一個文件名(沒有路徑),如何知道創建事件是在Faxfolder還是Faxfolder2上觸發的

System.out.println("START MONITORING  **************");


Path faxFolder = Paths.get("E:\\activiti\\monitor\\m1");
Path faxFolder2 = Paths.get("E:\\activiti\\monitor\\m2");
WatchService watchService = FileSystems.getDefault().newWatchService();
faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
faxFolder2.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);


boolean valid = true;
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();
        System.out.println(fileName);

    }
}

注冊watchService時,將為該目錄提供WatchKey 您應該記住哪個鍵與哪個目錄一起使用。

System.out.println("START MONITORING  **************");


Path faxFolder = Paths.get("E:\\activiti\\monitor\\m1");
Path faxFolder2 = Paths.get("E:\\activiti\\monitor\\m2");
WatchService watchService = FileSystems.getDefault().newWatchService();
Map<WatchKey,Path> keyMap = new HashMap<>();
WatchKey watchKey1 = faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
keyMap.put(watchKey1, faxFolder);
WatchKey watchKey2 = faxFolder2.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
keyMap.put(watchKey2, faxFolder2);


while (!Thread.currentThread().isInterrupted()) {
    WatchKey watchKey = watchService.take();
    Path dir = keyMap.get(watchKey);
    for (WatchEvent<?> event : watchKey.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
            Path relativePath = (Path) event.context();
            String fileName = dir.resolve(relativePath).toString();
            System.out.println(fileName);

        }
    }
}

您的監視循環應等待事件( WatchService.take() ),然后解決事件( watchKey.pollEvents() )。 所有這些都將適用於相同的WatchKey 然后,取下一個密鑰,該密鑰可能用於另一個目錄。

Path newFile = ev.context();
Path absolutePath = newFile.toAbsolutePath();

暫無
暫無

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

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