【发布时间】:2014-04-02 07:10:02
【问题描述】:
假设我有这样的功能:
public String runCommand(parameters, boolean interactive)
{
Process p = null;
// some code
try
{
final ProcessBuilder pb = new ProcessBuilder(my_command);
pb.inheritIO(); // So the output is displayed on the console
p = pb.start();
p.waitFor();
}
catch( IOException | InterruptedException e )
{
e.printStackTrace();
}
if (interactive )
{
return p.exitValue() + "";
}
else
{
// return the stdout of the process p
}
}
我要做的是返回我正在通过ProcessBuilder 运行的进程的标准输出,前提是interactive 布尔值设置为false。但是,我不知道如何将标准输出重定向到带有ProcessBuilder 的变量。请注意我使用了inheritIO(),所以当我使用adb shell 之类的函数时,shell 会显示在我的控制台中,这是我想要的行为。所以基本上,就目前而言,我可以在控制台中看到标准输出,但我不知道如何在函数中返回它,因此我可以将此值用作未来内容的变量。
【问题讨论】: