Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get output of "tail -f" command to java programme?

According to:

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

Java "tail -f" wrapper

I assume its possible but I have the following problem.

String TailCommand = "tail -f /path/PATH.txt| grep (...)";
Runtime r = Runtime.getRuntime();
Process p = r.exec(TailCommand);

//handle buffer

while (running) {
    // handle output
}

Process p terminates. It works fine with commands that doesnt have constant updates unlike "top" or "tail -f".

I wonder if I missed something, there is some buffer limitations or whatever? Im using eclipse but i guess that should not have any impact on process behavior.

In fact maybe there is another simply way to solve my issue that i missed. Im using "tail -f" since i have to analyze quite fat(some GBs) log thats constantly appending and dont intend to open it and read the whole file. I need only to controll the appending lines. However i found no suitable tail implementation

Thanks in advance.

like image 980
Abecede Abecede Avatar asked Nov 03 '22 04:11

Abecede Abecede


1 Answers

You can't execute piped commands from inside java.

If you want piped output, execute '/bin/sh' like this:

String tailCommand = "/bin/sh -c 'tail -f /path/PATH.txt| grep (...)'";

Also, your java program must consume the output of the process fast enough, so its buffers do not overflow.

You may want to read this article When Runtime.exec() won't, for description of common pitfalls when trying to execute a process from Java.

like image 135
Alexander Pogrebnyak Avatar answered Nov 09 '22 13:11

Alexander Pogrebnyak