Java“tail -f” 包装纸
我需要将 Unix 命令“tail -f”包装在 BufferedInputStream 中。 我不想模拟或模仿 这个问题< /a>. 相反,我想使用 tail,等待它给我一个新行。
I need to wrap the Unix command "tail -f" in a BufferedInputStream. I don't want to simulate or mimic tail as stated by this question. Rather, I want to use tail, waiting for it to give me a new line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
最好的选择是使用
Process
类并使用Scanner
读取:hasNextLine()
应该阻塞,因为它正在等待来自输入的更多输入流,这样您就不会忙于等待数据进入。Your best bet is to use the
Process
class and read with aScanner
:hasNextLine()
should block as it's waiting for more input from the input stream, so you will not be busy-waiting as data comes in.查看 Runtime.exec(字符串命令)。 返回具有输入和输出流的Process对象。
Look at Runtime.exec(String command). Returns a Process object that has Input and Output Streams.
另请检查 ProcessBuilder:
其中 < code>file 是类似“/var/log/messages”的字符串。
check also ProcessBuilder:
where
file
is String like "/var/log/messages".我猜测 system() 和 popen() 类型的方法将不起作用,因为它们会阻止您的程序,直到 tail 命令终止。
我认为您可以将输出重定向到一个文件,并针对最后一个版本使用“diff”来查看哪些行是新的?
I am guessing that system() and popen() type approaches will not work as they will block your program until the tail command terminates.
I think you could redirect the output to a file and use 'diff' against the last version to see which lines are new?
如果您有 unix 命令
,则尾部将显示为可能会阻塞一段时间的
InputStream
。 如果你不想阻止自己,你可以使用 nio 包。 我相信访问 tail 命令的大多数其他方法(例如 Process)都会产生类似的InputStream。If you have the unix command
Then the tail would appear as an
InputStream
that may block for a period of time. If you don't want to block yourself, you would use the nio packages. I believe that most other ways to access the tail command (such asProcess
) results in a similarInputStream
.另外两个完整的项目:
http://www.eclipse.org /tptp/home/documents/tutorials/gla/gettingstarted_gla.html
http://commons.apache.org/io/api-release/org/apache/commons/io/input/Tailer.html
Two more full blown projects:
http://www.eclipse.org/tptp/home/documents/tutorials/gla/gettingstarted_gla.html
http://commons.apache.org/io/api-release/org/apache/commons/io/input/Tailer.html