Java IO implementation of unix/linux "tail -f"

Gary picture Gary · Feb 17, 2009 · Viewed 73.4k times · Source

I'm wondering what techniques and/or library to use to implement the functionality of the linux command "tail -f ". I'm essentially looking for a drop in add-on/replacement for java.io.FileReader. Client code could look something like this:

TailFileReader lft = new TailFileReader("application.log");
BufferedReader br = new BufferedReader(lft);
String line;
try {
  while (true) {
    line= br.readLine();
    // do something interesting with line
  }
} catch (IOException e) {
  // barf
}

The missing piece is a reasonable implementation of TailFileReader. It should be able to read parts of the file that exist before the file is opened as well as the lines that are added.

Answer

Chetan S picture Chetan S · Feb 8, 2011

Take a look at Apache Commons implementation of Tailer class. It does seem to handle log rotation as well.