我需要执行一个外部应用程序,该应用程序返回大量数据(需要 2 个多小时才能完成)并且连续输出数据。
我需要做的是异步执行该程序并将输出捕获到文件中。
我尝试使用 java process builder,但是它似乎仅在程序退出或强制终止时才挂起并返回输出。
我尝试使用进程生成器并生成一个新线程来捕获输出,但仍然没有帮助。
然后我读到了 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 1
and echo
lines:
#!/bin/sh
sleep 1
echo "Hello"
sleep 1
echo "Hello"
...
从进程中读取的线程会输出一个Hello
每隔一秒左右。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)