java tail -f 后返回,是否有可能获得“tail -f”的输出?命令到java程序?

According to:

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值