Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 645
Gary Avatar asked Feb 17 '09 17:02

Gary


People also ask

How is tail command implemented in Java?

From main method start executor service to start log file tailer, i.e. crunchifyExecutor. execute(crunchify_tailF); which internally calls run() Also call appendData() method which will add new line to file every 5 seconds. Once new line will be added to file, tailer will pick and print it to Eclipse Console.

What is tail f command in Linux?

DESCRIPTION. tailf will print out the last 10 lines of a file and then wait for the file to grow. It is similar to tail -f but does not access the file when it is not growing.

What is tail in Unix command?

On Unix-like operating systems, the tail command reads a file, and outputs the last part of it (the "tail"). The tail command can also monitor data streams and open files, displaying new information as it is written. For example, it's a useful way to monitor the newest events in a system log in real time.


2 Answers

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

like image 193
Chetan S Avatar answered Sep 21 '22 12:09

Chetan S


The ability to continue to read a file, and wait around until the file has some more updates for you shouldn't be that hard to accomplish in code yourself. Here's some pseudo-code:

BufferedReader br = new BufferedReader(...); String line; while (keepReading) {     line = reader.readLine();     if (line == null) {         //wait until there is more of the file for us to read         Thread.sleep(1000);     }     else {         //do something interesting with the line     } } 

I would assume that you would want to put this type of functionality in its own Thread, so that you can sleep it and not affect any other areas of your application. You would want to expose keepReading in a setter so that your main class / other parts of the application can safely shut the thread down without any other headaches, simply by calling stopReading() or something similar.

like image 45
matt b Avatar answered Sep 19 '22 12:09

matt b