gpt4 book ai didi

java - java 7 nio 2 程序的意外输出

转载 作者:行者123 更新时间:2023-12-02 00:05:23 25 4
gpt4 key购买 nike

我正在尝试 Pro Java 7 NIO.2 中的一个小程序第118页

代码是:

class WatchRafaelNadal {
public void watchRNDir(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.take();
//get list of pending events for the watch key
for (WatchEvent<?> watchEvent : key.pollEvents()) {

//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
//print it out
System.out.println(kind + " -> " + filename);
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, for example)
if (!valid) {
break;
}
}
}
}
}

public class Main {
public static void main(String[] args) {
final Path path = Paths.get("C:/Java");
WatchRafaelNadal watch = new WatchRafaelNadal();
try {
watch.watchRNDir(path);
} catch (IOException | InterruptedException ex) {
System.err.println(ex);
}
}
}

但是当我更改文件夹 C:\\Java 中的 global.properties (或任何文件)中的一行时,我得到的输出为 -

 ENTRY_MODIFY  -> global.properties
ENTRY_MODIFY -> global.properties

为什么它会引发事件两次?
Java 中是否有任何服务可以检测文件中精确修改的行?

JDK:jdk1.7.0_09
IDE:Eclipse Java EE IDE 版本:Juno 版本
平台:Windows 7

最佳答案

你是如何更改文件的?

也许您从技术上更改了文件两次

例如,首先更改内容,然后更新文件元数据,这会产生两个事件。

最好以能够处理此类情况的方式实现应用程序。

关于java - java 7 nio 2 程序的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14002379/

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