使用Process Builder或Apache Commons exec执行外部程序 [英] Executing an external program using process builder or apache commons exec
问题描述
我需要执行一个外部应用程序,该应用程序将返回大数据(需要2个多小时才能完成),并连续输出数据.
I need to execute an external application which returns large data (takes more than 2 hours to complete ) nand which continuously outputs data.
我需要做的是异步执行该程序并将输出捕获到文件中. 我尝试使用Java流程生成器,但是它似乎仅在程序退出或强制终止时才挂起并返回输出.
What I need to do is execute this program asynchronously and capture the output in a file. I tried using java process builder, however it seems to hang and return output only when the program is exited or forcefully terminated.
我尝试使用流程生成器并修改了一个新线程来捕获输出,但是仍然没有帮助.
I tried to use process builder and spwaned a new thread to capture the output, but still it did not help.
然后,我了解了有关Apache Commons exec的信息,并尝试了相同的操作.但是,这似乎也要花费很长时间,并且返回不同的错误代码(对于相同的输入)
Then I read about apache commons exec and tried the same . however this also seems to be taking a long time and returns different error codes ( for the same input)
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();
}
任何有帮助的例子或有帮助的例子
Any help or working examples whould be very helpful
推荐答案
呵呵.使用ProcessBuilder
应该适合您的配置.例如,以下模式对我有用:
Huh. Using ProcessBuilder
should work for your configuration. For example, the following pattern works for me:
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
和echo
行的脚本:
The program that I'm running is just a script with a whole bunch of sleep 1
and echo
lines:
#!/bin/sh
sleep 1
echo "Hello"
sleep 1
echo "Hello"
...
从进程读取的线程大约每秒钟吐出一个Hello
.
The thread reading from the process spits out a Hello
every second or so.
这篇关于使用Process Builder或Apache Commons exec执行外部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!