gpt4 book ai didi

java - 当文件更改时,我读取文件,文件的内容始终相同?

转载 作者:行者123 更新时间:2023-12-01 16:24:55 25 4
gpt4 key购买 nike

我使用jdk1.8提供的watchevent来监听文件更改事件,但是当事件到来时,我读取了文件,但是文件的内容总是相同的?监视文件更改事件代码:

final WatchKey key = watcher.take();

for (WatchEvent<?> event : key.pollEvents()) {
// get event type
final WatchEvent.Kind<?> kind = event.kind();

// get file name
@SuppressWarnings("unchecked") final WatchEvent<Path> pathWatchEvent = (WatchEvent<Path>) event;
final Path fileName = pathWatchEvent.context();

if (kind == ENTRY_DELETE) {
log.info(String.format("%s文件被删除",fileName));
} else if (kind == ENTRY_MODIFY) {
log.info(fileName.toString());
log.info("ENTRY_MODIFY");
if (Constant.ERROR_LOG.equals(fileName.toString())) {
String filePath = "\\\\192.168.160.128\\share\\error_log";
int totalLine = FileUtils.countFileTotalLine(filePath);

读取文件代码:

File file = new File(sourceFilePath);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
StringBuilder strBuilder = new StringBuilder();
String sLine = null;
while ((sLine = br.readLine()) != null) {
strBuilder.append(sLine);
strBuilder.append("\r\n");
}

最佳答案

我的应用程序在使用 Watcher 服务等待文件上的 kind == ENTRY_MODIFY 时遇到了类似的问题,但没有像您遇到的 3 分钟延迟那样。您的代码不完整,因此不清楚是否缺少一个重要的位来解释延迟,因此很高兴看到完整的代码。

不幸的是,观察者服务可能会为每个文件生成大量事件,尤其是 ENTRY_MODIFY。我发现在循环中调用 watcher.poll(timeout) 并整理一组接收到的事件要可靠得多。仅当 set 变大时才执行一次,或者 watcher.poll 返回 null 时,或者自上次处理以来的某个时间间隔。像这样的东西:

var modified = new HashSet<Path>();
while(runningFlag) {
WatchKey k = ws.poll(modified.size() == 0 ? 10 : 1, TimeUnit.SECONDS);
if (k != null) {
// Loop through the ENTRY_MODIFY events as before but save the items:
... modified.add(fileName);
if (!k.reset()) { ... handle reconnection }
}

if (modified.size() > 0 && (k == null || modified.size() > limit)) {
// Act on modifications set
...
modified.clear();
}
}

这将减少您执行的事件数量,尽管您可能还需要处理其他一些网络安装/缓存问题。

关于java - 当文件更改时,我读取文件,文件的内容始终相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62167814/

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