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

标签 java file bufferedreader inputstreamreader

我使用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/

相关文章:

java - 如何使用原因定义 “isValid”函数

php - 密码保护目录,但仍允许在主页上使用

java - 从 .jar 文件读取文本文件

sockets - BufferedReader-在流的末尾阻塞

java - 读取/写入文件时如何克服硬件限制。

java - 如何使用 rally rest api 查找给定迭代和给定项目下的用户故事列表

java - Swing:单击一个框架中的按钮,显示具有不同组件的另一个框架

java - Junit 在 Suite 类之间共享外部资源

将 .txt 文件中的唯一词复制到链表

python - 需要代码仅返回目录名称