调用 Runtime.exec 时捕获标准输出 [英] Capturing stdout when calling Runtime.exec

查看:37
本文介绍了调用 Runtime.exec 时捕获标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在客户端机器上遇到网络问题时,我希望能够运行几个命令行并将结果通过电子邮件发送给我自己.

When experiencing networking problems on client machines, I'd like to be able to run a few command lines and email the results of them to myself.

我发现 Runtime.exec 将允许我执行任意命令,但将结果收集到一个字符串中更有趣.

I've found Runtime.exec will allow me to execute arbitrary commands, but Collecting the results in a String is more interesting.

我意识到我可以将输出重定向到一个文件,然后从该文件中读取,但我的诡异感告诉我有一种更优雅的方式来做到这一点.

I realize I could redirect output to a file, and then read from the file, but my spidey sense is telling me there's a more elegant way of doing it.

建议?

推荐答案

您需要同时捕获过程中的 std out 和 std err.然后,您可以将标准输出写入文件/邮件或类似文件.

You need to capture both the std out and std err in the process. You can then write std out to a file/mail or similar.

请参阅这篇文章有关更多信息,请特别注意 StreamGobbler 机制,它在单独的线程中捕获 stdout/err.这对于防止阻塞至关重要,如果操作不当,则会导致许多错误!

See this article for more info, and in particular note the StreamGobbler mechanism that captures stdout/err in separate threads. This is essential to prevent blocking and is the source of numerous errors if you don't do it properly!

这篇关于调用 Runtime.exec 时捕获标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆