当文件发生变化时,我读取文件,但是文件的内容总是一样的?

问题描述 投票:0回答:1

我使用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");
}
java file bufferedreader inputstreamreader
1个回答
0
投票

我的应用程序在使用Watcher服务时也出现过类似的问题,当它在文件上等待kind == ENTRY_MODIFY时,但没有像你这样3分钟的滞后。你的代码是不完整的,所以不清楚是否缺少了一个重要的位子来解释这个滞后,所以最好能看到完整的代码。

不幸的是,watcher服务可以在每个文件中产生大量的事件,尤其是ENTRY_MODIFY。我发现在一个循环中调用watcher.poll(timeout),并将收到的事件整理成一个集合,这样做更可靠。只有在事件集变大,或者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();
    }
}

这样可以减少你处理事件的数量 尽管你可能还要处理一些其他的网络挂载缓存问题

© www.soinside.com 2019 - 2024. All rights reserved.