gpt4 book ai didi

java - InputStream 和 StreamGobbler 有什么区别?

转载 作者:行者123 更新时间:2023-12-01 09:36:39 26 4
gpt4 key购买 nike

在下面的代码中,作者使用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();

最佳答案

即使我不知道 StreamGobbler 类,这显然是一个线程实现,用于将输出和错误流复制到给定目标。因此,不,你不能简单地替换它,因为多线程确实是必要的。一个简单的输入流只是坐在那里,但实际上不执行任何操作。

但请注意,自 Java 1.5 引入 ProcessBuilder 和自动重定向以来,这个完整的解决方案已经过时了。请参阅 javadoc https://docs.oracle.com/javase/8/docs/api/

关于java - InputStream 和 StreamGobbler 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38843022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com