我正在使用 inotify nio 包装器来捕获特定目录中的文件创建。好的,我有这个
private final String tmpDir1 = Files.createTempDirectory(null);
private final String tmpDir2 = Files.createTempDirectory(null);
WatchService watchService = FileSystems.getDefault.newWatchService()
Paths.get(tmpDir1).register(watchService, ENTRY_CREATE)
Paths.get(tmpDir2).register(watchService, ENTRY_CREATE)
public String getModifiedFilePath(){
WatchKey key = ((WatchEvent<Path>) watchService.take())
//Does p belongs to tmpDir1 or tmpDir2?
Path p = ((WatchEvent<Path>)(key.pollEvents().iterator().next())).context()
return //???
}
如方法文档中所指定 WatchEvent#context
Returns the context for the event. In the case of
ENTRY_CREATE
,ENTRY_DELETE
, andENTRY_MODIFY
events the context is aPath
that is the relative path between the directory registered with the watch service, and the entry that is created, deleted, or modified.
但是 sun.nio.fs.AbstractWatchKey
包含字段 private final Path dir
。但是这个类是包私有(private)的。有没有办法获取 WatchEvent#context
返回的文件所属的目录名?
UPD:为我想观看的每个目录创建 inotify 实例听起来真的很奇怪。
最佳答案
享受
public Path getModifiedFilePath() throws InterruptedException {
WatchKey key = watchService.take();
return (Path) key.watchable();
}
关于java - 监听多个目录以在 Java 中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878391/