阅读 WatchEvent
的 javadoc,我看到 count()
方法让我知道事件的结果是否重复。
Returns the event count. If the event count is greater than 1 then this is a repeated event.
这到底是什么意思?这是否意味着两个或多个 WatchEvent
对象引用同一个“事件”(例如正在创建的文件)?
我正在试验 example在 Oracle 的网站上为新的 WatchService
API 而这部分让我感到困惑,特别是因为我将在连续运行相同的测试代码时得到不同数量的事件(我在其中使用 FileWriter
而无需手动与之交互),但 count()
的结果永远不会超过 1。
编辑:我意识到这可能与 this other question about repeated events 有关,但这并没有回答重复事件的实际含义。
最佳答案
我花了一段时间对此进行试验,这是我的结论:
An event is repeated, for file
f
and event typee
, if multiplee
type events occurred to the same filef
.If an
e
type event occurred to multiple filesf1
,f2
, andf3
, but only once each, then none of those events are repeated.
当您从 WatchService
.take()
一个 WatchKey
时,您将获得一个 WatchEvent
经历过事件的文件,对于它经历过的每种事件类型。如果自上次从 WatchService
获取 WatchKey
以来该文件多次发生该类型的事件,则 .count()
将大于 1 >.
也就是说,如果您正在观看一个包含 A.txt
的目录,然后会发生以下事件:
B.txt
在目录下创建。B.txt
写入。A.txt
写入。B.txt
被删除。A.txt
再次写入。
你会得到四个WatchEvents
:
B.txt
的创建事件。B.txt
的修改事件。A.txt
的修改事件。它的.count()
将为 2。B.txt
的删除事件。
这意味着您永远不会在您的 WatchKey
中获得超过 3*n
个事件,其中 n
是在目录中的任何位置。
StandardWatchEventKinds
中定义了四种类型的事件, 但 OVERFLOW
事件表明事件可能已经丢失,所以我从上面的数字中省略了它。
关于java - 事件为 "repeated?"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21998659/