在Java中,监视附加到的文件的最佳/最安全模式是什么? [英] In Java, what is the best/safest pattern for monitoring a file being appended to?

查看:116
本文介绍了在Java中,监视附加到的文件的最佳/最安全模式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他人的过程是在事件发生时通过一次添加一行来创建CSV文件。我无法控制文件格式或其他进程,但我知道它只会附加。

Someone else's process is creating a CSV file by appending a line at a time to it, as events occur. I have no control over the file format or the other process, but I know it will only append.

在Java程序中,我想监视这个文件,当附加一行时,读取新行并根据内容做出反应。暂时忽略CSV解析问题。监视文件以进行更改并一次读取一行的最佳方法是什么?

In a Java program, I would like to monitor this file, and when a line is appended read the new line and react according to the contents. Ignore the CSV parsing issue for now. What is the best way to monitor the file for changes and read a line at a time?

理想情况下,这将使用标准库类。该文件可能在网络驱动器上,所以我想要一些强大的失败。如果可能的话,我宁愿不使用轮询 - 我更喜欢某种阻塞解决方案。

Ideally this will use the standard library classes. The file may well be on a network drive, so I'd like something robust to failure. I'd rather not use polling if possible - I'd prefer some sort of blocking solution instead.

编辑 - 鉴于标准类无法实现阻塞解决方案(感谢您的回答),最强大的轮询解决方案是什么?我不想每次都重新读取整个文件,因为它可能会变得非常大。

Edit -- given that a blocking solution is not possible with standard classes (thanks for that answer), what is the most robust polling solution? I'd rather not re-read the whole file each time as it could grow quite large.

推荐答案

自Java 7以来是 newWatchService( ) FileSystem类上的方法。

Since Java 7 there has been the newWatchService() method on the FileSystem class.

但是,有一些警告:


  • 它只是Java 7

  • 这是一个可选方法

  • 它只监视目录,所以你必须自己做文件处理,并担心文件移动等

在Java 7之前,标准API无法实现。

Before Java 7 it is not possible with standard APIs.

我尝试了以下(1秒间隔轮询)并且它可以正常工作(只是在处理中打印):

I tried the following (polling on a 1 sec interval) and it works (just prints in processing):

  private static void monitorFile(File file) throws IOException {
    final int POLL_INTERVAL = 1000;
    FileReader reader = new FileReader(file);
    BufferedReader buffered = new BufferedReader(reader);
    try {
      while(true) {
        String line = buffered.readLine();
        if(line == null) {
          // end of file, start polling
          Thread.sleep(POLL_INTERVAL);
        } else {
          System.out.println(line);
        }
      }
    } catch(InterruptedException ex) {
     ex.printStackTrace();
    }
  }

因为没有其他人建议使用的解决方案当前生产Java我以为我会添加它。如果有缺陷,请在评论中添加。

As no-one else has suggested a solution which uses a current production Java I thought I'd add it. If there are flaws please add in comments.

这篇关于在Java中,监视附加到的文件的最佳/最安全模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆