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

烂漫一生 提交于 2019-12-13 12:28:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/14822302/is-it-possible-to-get-output-of-tail-f-command-to-java-programme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!