gpt4 book ai didi

java - 监听多个目录以在 Java 中创建文件

转载 作者:行者123 更新时间:2023-11-29 04:20:10 25 4
gpt4 key购买 nike

我正在使用 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, and ENTRY_MODIFY events the context is a Path 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com