在下面的代码中,作者使用Runtime
来调用子流程。但我不明白为什么他会使用StreamGobbler
。如果用InputStream
替换它会发生什么?请帮助我,谢谢!
public class GoodWindowsExec
{
public static void main(String args[])
{
try
{
String osName = System.getProperty("os.name" );
System.out.println("osName: " + osName);
String[] cmd = new String[3];
if(osName.equals("Windows XP") ||osName.equals("Windows 2000"))
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Windows 98" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]+ " " + cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); //Can I replace StreamGobbler by InputStream?
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); //As above
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t){
t.printStackTrace();
}
}
}
BufferedReader brNormal = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = brNormal.readLine()) != null) {
logger.info("RawToRgbConverter.exe", s);
}
brNormal.close();
BufferedReader brError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((s = brError.readLine()) != null) {
logger.error("RawToRgbConverter.exe", s);
}
brError.close();
答案 0 :(得分:1)
即使我不了解StreamGobbler类,这显然是一个将输出和错误流复制到给定目标的线程实现。因此,不能简单地替换它,因为多线程确实是必要的。一个简单的输入流只会坐在那里,但实际上并没有做任何事情。
但请注意,自Java 1.5引入ProcessBuilder和自动重定向以来,这个完整的解决方案已经过时了。请参阅https://docs.oracle.com/javase/8/docs/api/
上的javadoc