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

标签 java file jvm nio

我正在使用 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/

相关文章:

java - 可能因不同原因而失败的方法的标准模式是什么?

python - 无法从 CPython 读取巨大(20GB)文件

Java CMS 被忽略,取而代之的是 Full GC

java - JVM 执行应用程序时是否多次读取 jar 文件?

java - JVM 可以在不重新启动的情况下从 OutOfMemoryError 中恢复吗

JavaEE、Servlet 创建指向文件夹中文件的链接

java - 如何使可变对象列表不可变

java - Spring Boot通过 JDBC 语句执行 DDL 删除架构时出错

python - 统计文件中单词的出现次数

windows - 删除运行时正在使用的文件