在Java中侦听多个目录以创建文件
我使用inotifnio包装器捕获特定目录中的文件创建。好的,我有这个在Java中侦听多个目录以创建文件,java,file,jvm,nio,Java,File,Jvm,Nio,我使用inotifnio包装器捕获特定目录中的文件创建。好的,我有这个 private final String tmpDir1 = Files.createTempDirectory(null); private final String tmpDir2 = Files.createTempDirectory(null); WatchService watchService = FileSystems.getDefault.newWatchService() Paths.get(tmpDi
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 //???
}
private final String tmpDir1=Files.createTempDirectory(null);
私有最终字符串tmpDir2=Files.createTempDirectory(null);
WatchService WatchService=FileSystems.getDefault.newWatchService()
path.get(tmpDir1).register(watchService,ENTRY\u CREATE)
path.get(tmpDir2).register(watchService,ENTRY\u CREATE)
公共字符串getModifiedFilePath(){
WatchKey key=((WatchEvent)watchService.take())
//p属于tmpDir1还是tmpDir2?
路径p=((WatchEvent)(key.pollEvents().iterator().next()).context()
返回/???
}
如方法WatchEvent#context
返回事件的上下文。如果是条目\u创建
,
ENTRY\u DELETE
和ENTRY\u MODIFY
事件上下文是一个路径,即
向手表注册的目录之间的相对路径
服务,以及创建、删除或修改的条目
但是sun.nio.fs.AbstractWatchKey
包含字段private final Path dir
。但是这个类是包私有的。是否有方法获取由WatchEvent#context
返回的文件所属的目录名
UPD:为我想看的每个目录创建inotify实例听起来真的很有趣。享受吧
public Path getModifiedFilePath() throws InterruptedException {
WatchKey key = watchService.take();
return (Path) key.watchable();
}
通过使用Java反射API,您可以修改访问修饰符。
coool。多谢!