gpt4 book ai didi

java - WatchService/WatchEvent/事件路径

转载 作者:搜寻专家 更新时间:2023-11-01 03:11:56 26 4
gpt4 key购买 nike

我递归地观察一个目录(以及所有子目录和文件)的变化。

看来,如果我在根目录的子目录中创建或删除目录或文件以查看包含在 WatchEvent 实例中的路径,那么接收到的实例(通过上下文())没有父级,因此 rootDirToWatch.resolve(event.context()) 没有返回我喜欢的路径。

例如:

/home/johannes/test 被监视,然后我在 /home/johannes/test/foo/bar 中创建一个名为 baz 的新目录,我得到一个新的 Path 实例,它是/home/johannes/test/baz 而不是 /home/johannes/test/foo/bar/baz

有什么问题的建议吗?

我只是使用访问者来监视某个根目录中的所有子目录以进行监视(监视整个目录及其所有后代):

@Override
public FileVisitResult preVisitDirectory(final Path pDir, final BasicFileAttributes pAttrs)
throws IOException
{
checkNotNull(pDir);
checkNotNull(pAttrs);
pDir.register(mWatcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return FileVisitResult.CONTINUE;
}

编辑:我认为我真的必须使用访问者或至少向观察者注册所有子目录。由于 WatchEvent 返回一个相对路径,所以很清楚为什么它的行为与描述的一样,但我不想再次遍历目录以找到从根目录到要在层次结构中某处添加/删除/修改文件的路径.

编辑:我找到了解决方案(“索引”键):http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

最佳答案

艾伦是对的。

您应该在 key 中使用 Watchable。

这是来 self 的应用程序的 Scala 代码。我想您将能够阅读它。

object FsNotifType extends Enumeration {
val Create, Update, Delete = Value
}

case class FsNotif(notifType: FsNotifType.Value,path: Path)

object FsNotif {
def apply(watchKey: WatchKey,event: java.nio.file.WatchEvent[_]): FsNotif = {
val fsNotifType = event.kind() match {
case StandardWatchEventKinds.ENTRY_CREATE => FsNotifType.Create
case StandardWatchEventKinds.ENTRY_MODIFY => FsNotifType.Update
case StandardWatchEventKinds.ENTRY_DELETE => FsNotifType.Delete
case _ => throw new IllegalStateException("Unknown FS event kind: " + event)
}
val watchedPath = watchKey.watchable().asInstanceOf[Path]
val relativePath = event.context().asInstanceOf[Path]
val absolutePath = watchedPath.resolve(relativePath)
FsNotif(fsNotifType,absolutePath)
}
}

这工作正常,但要注意一些极端情况:

/**
* Returns the object for which this watch key was created. This method will
* continue to return the object even after the key is cancelled.
*
* <p> As the {@code WatchService} is intended to map directly on to the
* native file event notification facility (where available) then many of
* details on how registered objects are watched is highly implementation
* specific. When watching a directory for changes for example, and the
* directory is moved or renamed in the file system, there is no guarantee
* that the watch key will be cancelled and so the object returned by this
* method may no longer be a valid path to the directory.
*
* @return the object for which this watch key was created
*/
Watchable watchable();

抱歉,我不知道该如何处理。

关于java - WatchService/WatchEvent/事件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8205842/

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