【发布时间】:2010-11-18 01:45:07
【问题描述】:
不使用重定向到文件 (">", ">>")
【问题讨论】:
不使用重定向到文件 (">", ">>")
【问题讨论】:
Process p = Runtime.getRuntime().exec("executable.exec");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
【讨论】:
while循环之后添加p.waitFor()。
请注意,您应该同时使用 stdout 和 stderr,以防止阻塞。详情请见this answer。
请注意,您可以只使用 stdout 而不是 stderr。但是,如果您的 .exe 在某些情况下生成错误,那么您的父进程可以阻止额外(意外)流数据。因此,最好同时运行您的流收集。
【讨论】:
如果您使用来自plexus-utils 的命令行类型,您可以避免很多与命令行交互相关的繁重工作,例如等待进程、转义参数等。如果需要,您也可以将命令设置为超时.
您可以通过 StreamConsumers 来捕获 stdout 和 stderr,命令行处理会将输出一次传递给消费者。
Commandline cl = new Commandline();
cl.setExecutable( "dir" );
cl.setWorkingDirectory( workingDirectory.getAbsolutePath() );
cl.createArg().setValue( "/S" );
StreamConsumer consumer = new StreamConsumer() {
public void consumeLine( String line ) {
//do something with the line
}
};
StreamConsumer stderr = new StreamConsumer() {
public void consumeLine( String line ) {
//do something with the line
}
};
int exitCode;
try {
exitCode = CommandLineUtils.execute( cl, consumer, stderr, getLogger() );
} catch ( CommandLineException ex ) {
//handle exception
}
【讨论】: