In Java, what is the best/safest pattern for monitoring a file being appended to?

file, java, nio

Solution

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

However, there are some caveats:

- It is only Java 7

- It is an optional method

- it only watches directories, so you have to do the file handling yourself, and worry about the file moving etc

Before Java 7 it is not possible with standard APIs.

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();
    }
  }

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.

Problem

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. 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.

Original source

Related problems