调用Runtime.exec时捕获stdout [英] Capturing stdout when calling Runtime.exec

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

问题描述

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

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。然后,您可以将std写入文件/邮件或类似文件。

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时捕获stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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