gpt4 book ai didi

java - WatchService - 错误解析的绝对路径

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:08:07 26 4
gpt4 key购买 nike

我一直在研究 java.nio.file.WatchService并注意到 Path s 从 WatchEvent.context() 返回不返回正确的 .toAbsolutePath() .这是一个示例应用程序:

public class FsWatcher {
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 1) {
System.err.println("Invalid number of arguments: " + args.length);
return;
}
//Run the application with absolute path like /home/<username>
final Path watchedDirectory = Paths.get(args[0]).toAbsolutePath();
final FileSystem fileSystem = FileSystems.getDefault();
final WatchService watchService = fileSystem.newWatchService();
watchedDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

while (true) {
WatchKey watchKey = watchService.take();
for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
if (watchEvent.kind().equals(StandardWatchEventKinds.OVERFLOW)) {
continue;
}

final Path createdFile = (Path) watchEvent.context();
final Path expectedAbsolutePath = watchedDirectory.resolve(createdFile);
System.out.println("Context path: " + createdFile);
System.out.println("Context absolute path: " + createdFile.toAbsolutePath());
System.out.println("Expected absolute path: " + expectedAbsolutePath);
System.out.println("usr.dir: " + System.getProperty("user.dir"));
}
watchKey.reset();
}
}
}

示例输出:

Context path: document.txt
Context absolute path: /home/svetlin/workspaces/default/FsWatcher/document.txt
Expected absolute path: /home/svetlin/document.txt
usr.dir: /home/svetlin/workspaces/default/FsWatcher

看来绝对路径是针对 user.dir 解析的系统属性而不是 Path用于 WatchService登记。这是一个问题,因为当我尝试使用(例如 Files.copy() )从 WatchEvent 返回的路径时我收到 java.nio.file.NoSuchFileException ,这是预期的,因为在此路径中没有这样的文件。我是否遗漏了什么或者这是 JRE 中的错误?

最佳答案

这不是错误,但确实令人困惑。

如果 WatchEvent.context() 返回一个 Path 那么它是相对的:

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.

现在,如果您通过调用 toAbsolutePath() 将这样的路径转换为绝对路径,这不是相对于监视目录而是相对于默认目录发生的。

This method resolves the path in an implementation dependent manner, typically by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.

因此要把路径变成绝对路径就需要用到

watchedDirectory.resolve(createdFile);

关于java - WatchService - 错误解析的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32691350/

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