UNIX “tail -f” functionality in Java

UNIX “tail -f” functionality in Java

Overview

If it’s needed to monitor lines appended to the end of the file, UNIX utility “tail” with “-f” parameter is usually used to achieve that. Here is an example:

tail -f /var/log/auth.log

What if it’s needed not only to monitor lines, but also to process them in your application ? Luckily, there are easy-to-use solutions and one of them is going to be discovered in this article. Apache Commons IO provides a functionality that solves the problem mentioned above.

Dependencies

First of all, corresponding dependency has to be added:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

Application

Let’s create an application that processes lines appended to the end of the file.

public class TailerApp {
    private static class NewLineListener extends TailerListenerAdapter {
        @Override
        public void handle(String line) {
            System.out.println(line);
        }
    }

    private final File file;
    private final long delay;
    private final TailerListenerAdapter newLineHandler;

    public TailerApp(File file, long delay, TailerListenerAdapter newLineHandler) {
        this.file = file;
        this.delay = delay;
        this.newLineHandler = newLineHandler;
    }
    public void run() {
        Tailer tailer = new Tailer(file, newLineHandler, delay);
        tailer.run();
    }
    public static void main(String[] args) {
        TailerApp tailer = new TailerApp(new File("test.txt"), 500, new NewLineListener());
        tailer.run();
    }
}


Three parameters have to be specified:

  • file for monitoring
  • delay (how often to check for file changes)
  • callback to process new lines

To test the application let’s run it and execute the following commands in the same folder:

echo -e "test1" >> test.txt
echo -e "test2" >> test.txt
echo -e "test3" >> test.txt

These commands append line to the end of the file called “test.txt” and we expect to see them processed by our application.

Let’s have a look at the application output:

test1
test2
test3

So, application has successfully detected new lines in the file and processed them

Leave a Reply

Your email address will not be published. Required fields are marked *