Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中侦听多个目录以创建文件_Java_File_Jvm_Nio - Fatal编程技术网

在Java中侦听多个目录以创建文件

在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

我使用inotifnio包装器捕获特定目录中的文件创建。好的,我有这个

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。多谢!