使用流程构建器或apache commons exec执行外部程序

我需要执行一个外部应用程序,它返回大量数据(需要2个多小时才能完成)并连续输出数据。

我需要做的是异步执行该程序并捕获文件中的输出。 我尝试使用java进程构建器,但它似乎挂起并仅在程序退出或强制终止时返回输出。

我尝试使用进程构建器并spwaned一个新的线程来捕获输出,但它仍然没有帮助。

然后我读了关于apache commons exec并尝试了同样的事情。 然而,这似乎也需要很长时间并返回不同的错误代码(对于相同的输入)

CommandLine cmdLine = new CommandLine("/opt/testsimulator"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000); Executor executor = new DefaultExecutor(); executor.setStreamHandler(psh); executor.setWatchdog(watchdog); try { executor.execute(cmdLine); } catch (ExecuteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

任何帮助或工作示例都会非常有用

呵呵。 使用ProcessBuilder应该适用于您的配置。 例如,以下模式适用于我:

 ProcessBuilder pb = new ProcessBuilder("/tmp/x"); Process process = pb.start(); final InputStream is = process.getInputStream(); // the background thread watches the output from the process new Thread(new Runnable() { public void run() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { is.close(); } } }).start(); // the outer thread waits for the process to finish process.waitFor(); 

我正在运行的程序只是一个带有一大堆sleep 1echo行的脚本:

 #!/bin/sh sleep 1 echo "Hello" sleep 1 echo "Hello" ... 

从进程读取的线程每隔一秒左右吐出一个Hello