我需要将 Unix 命令“tail -f”包装在 BufferedInputStream 中。我不想像这个问题所说的那样模拟或模仿尾巴。相反,我想使用tail,等待它给我一个新行。
6 回答
您最好的选择是使用该Process
课程并阅读Scanner
:
Runtime r = Runtime.getRuntime()
Process p = r.exec("tail -f")
Scanner s = new Scanner(p.getInputStream())
while (s.hasNextLine()) {
String line = s.nextLine()
// Do whatever you want with the output.
}
hasNextLine()
应该阻塞,因为它正在等待来自输入流的更多输入,因此您不会在数据进入时忙于等待。
查看 Runtime.exec(字符串命令)。返回具有输入和输出流的Process对象。
还要检查ProcessBuilder:
Process tail = new ProcessBuilder("tail", "-f", file).start();
BufferedInputStream bis = new BufferedInputStream(tail.getInputStream())
file
像“/var/log/messages”这样的字符串在哪里。
我猜 system() 和 popen() 类型的方法将不起作用,因为它们会阻止您的程序,直到 tail 命令终止。
我认为您可以将输出重定向到文件并针对上一个版本使用“diff”来查看哪些行是新的?
如果你有 unix 命令
tail -f <file> | <some java program>
然后尾巴会显示为InputStream
可能会阻塞一段时间。如果您不想阻止自己,则可以使用 nio 包。我相信大多数其他访问 tail 命令的方法(例如Process
)都会导致类似的InputStream
.
还有两个成熟的项目:
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