如何获取exe文件生成的控制台输出?

不使用重定向文件(“>”,“>>”)

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); } 

请注意,您应该同时使用stdout和stderr,以防止阻塞。 有关详细信息,请参阅此答案 。

请注意,您可以通过stdout而不是stderr来逃脱。 但是,如果.exe在某些情况下生成错误,则父进程可以阻止额外(意外)流数据。 因此,最好同时运行流收集。

如果使用来自plexus-utils的命令行类型,则可以避免与命令行交互相关的大量繁重工作,例如等待进程,转义参数等。如果需要,可以将命令设置为超时。

您可以传递StreamConsumers来捕获stdout和stderr,Commandline处理将一次将输出传递给消费者。

 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 }