我想获得一个进程的输出(Git.exe
准确地说)并将其转换为 String 对象。以前有时我的代码被阻止。然后我发现这是因为这个过程'ErrorStream
有一些输出,我必须手动捕获它(我对此不感兴趣)。我将我的代码更改为:
public static String runProcess(String executable, String parameter) {
try {
String path = String.format("%s %s", executable, parameter);
Process pr = Runtime.getRuntime().exec(path);
// ignore errors
StringWriter errors = new StringWriter();
IOUtils.copy(pr.getErrorStream(), errors);
StringWriter writer = new StringWriter();
IOUtils.copy(pr.getInputStream(), writer);
pr.waitFor();
return writer.toString();
} catch (Exception e) {
return null;
}
}
现在它大部分工作正常,但话又说回来,有时它会在这一行再次被阻止:IOUtils.copy(pr.getErrorStream(), errors);
.
有什么方法可以让我得到输出git.exe
不撞块?谢谢。
使用这个漂亮的文章和StreamGobbler
那里描述的类(我修改了一点)我解决了问题。我的实施StreamGobbler
:
class StreamGobbler extends Thread {
InputStream is;
String output;
StreamGobbler(InputStream is) {
this.is = is;
}
public String getOutput() {
return output;
}
public void run() {
try {
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer);
output = writer.toString();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
我的功能是:
public static String runProcess(String executable, String parameter) {
try {
String path = String.format("%s %s", executable, parameter);
Process pr = Runtime.getRuntime().exec(path);
StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream());
StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream());
// kick them off concurrently
errorGobbler.start();
outputGobbler.start();
pr.waitFor();
return outputGobbler.getOutput();
} catch (Exception e) {
return null;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)