Java“tail -f” 包装纸

发布于 2024-07-24 09:32:48 字数 207 浏览 5 评论 0原文

我需要将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

子栖 2024-07-31 09:32:48

最好的选择是使用 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() 应该阻塞,因为它正在等待来自输入的更多输入流,这样您就不会忙于等待数据进入。

Your best bet is to use the Process class and read with a 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() should block as it's waiting for more input from the input stream, so you will not be busy-waiting as data comes in.

往事随风而去 2024-07-31 09:32:48

查看 Runtime.exec(字符串命令)。 返回具有输入和输出流的Process对象。

Look at Runtime.exec(String command). Returns a Process object that has Input and Output Streams.

微凉 2024-07-31 09:32:48

另请检查 ProcessBuilder

Process tail = new ProcessBuilder("tail", "-f", file).start();
BufferedInputStream bis = new BufferedInputStream(tail.getInputStream())

其中 < code>file 是类似“/var/log/messages”的字符串。

check also ProcessBuilder:

Process tail = new ProcessBuilder("tail", "-f", file).start();
BufferedInputStream bis = new BufferedInputStream(tail.getInputStream())

where file is String like "/var/log/messages".

弄潮 2024-07-31 09:32:48

我猜测 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?

相思碎 2024-07-31 09:32:48

如果您有 unix 命令

tail -f <file> | <some java program>

,则尾部将显示为可能会阻塞一段时间的InputStream。 如果你不想阻止自己,你可以使用 nio 包。 我相信访问 tail 命令的大多数其他方法(例如 Process)都会产生类似的InputStream。

If you have the unix command

tail -f <file> | <some java program>

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 as Process) results in a similar InputStream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文