[英]Java Runtime.exec() asynchronous output
我想从长时间运行的shell命令获取输出,因为它可用而不是等待命令完成。 我的代码在一个新线程中运行
Process proc = Runtime.getRuntime().exec("/opt/bin/longRunning");
InputStream in = proc.getInputStream();
int c;
while((c = in.read()) != -1) {
MyStaticClass.stringBuilder.append(c);
}
这个问题是我的/ opt / bin / longRunning中的程序必须在分配和读取InputStream之前完成。 是否有任何好方法异步执行此操作? 我的目标是ajax请求每隔一秒左右返回当前值MyStaticClass.stringBuilder.toString()。
我坚持使用Java 5,fyi。
谢谢! w ^
尝试使用Apache Common Exec 。 它具有异步执行进程然后将输出“泵”到线程的能力。 查看Javadoc以获取更多信息
调用Runtime.getRuntime()。执行不会等待命令终止,所以你应该得到的输出,立竿见影。 也许输出是缓冲的,因为命令知道它正在写入管道而不是终端?
把阅读放在一个新的线程中:
new Thread() {
public void run() {
InputStream in = proc.getInputStream();
int c;
while((c = in.read()) != -1) {
MyStaticClass.stringBuilder.append(c);
}
}
}.start();
你写的是你打电话的节目吗? 如果是这样,请在写入后尝试刷新输出。 文本可能会卡在缓冲区中,而不是到达您的java程序。
我使用此代码执行此操作,它的工作原理:
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while (true) {
// enter a loop where we read what the program has to say and wait for it to finish
// read all the program has to say
while (br.ready()) {
String line = br.readLine();
System.out.println("CMD: " + line);
}
try {
int exitCode = proc.exitValue();
System.out.println("exit code: " + exitCode);
// if we get here then the process finished executing
break;
} catch (IllegalThreadStateException ex) {
// ignore
}
// wait 200ms and try again
Thread.sleep(200);
}
试试:
try {
Process p = Runtime.getRuntime().exec("/opt/bin/longRunning");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.