Java commons exec:调用executor.execute(命令行)时挂起;
我不知道为什么要挂起来。我试图捕获通过CommonsExec运行的进程的输出,但仍然挂起。下面我提供了一个示例程序来演示这种行为Java commons exec:调用executor.execute(命令行)时挂起;,java,multithreading,apache-commons-exec,Java,Multithreading,Apache Commons Exec,我不知道为什么要挂起来。我试图捕获通过CommonsExec运行的进程的输出,但仍然挂起。下面我提供了一个示例程序来演示这种行为 import java.io.DataInputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import org.apache.commons.exec.CommandLine; import org.apa
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;
public class test {
public static void main(String[] args) {
String command = "java";
PipedOutputStream output = new PipedOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(output);
CommandLine cl = CommandLine.parse(command);
DefaultExecutor exec = new DefaultExecutor();
DataInputStream is = null;
try {
is = new DataInputStream(new PipedInputStream(output));
exec.setStreamHandler(psh);
exec.execute(cl);
} catch (ExecuteException ex) {
} catch (IOException ex) {
}
System.out.println("huh?");
}
}
根据,
execute(CommandLine命令)
是同步的,execute(CommandLine命令,executesUltHandler处理程序)
另一方面是异步的。您调用的命令,java
,生成标准输出流的输出。调用程序必须将该流泵入输入流。这在您的程序中不会发生
您必须在单独的线程中读取输入流(在代码中是
),因为管道流就是这样工作的。请注意,在调用execute()
之前,必须先启动读取线程
另见
根据您的另一个问题,您需要大数据,因此必须使用管道流,而不能使用更简单的方法,即使用ByteArrayInputStream
作为输出。你给自己的答案和这里的代码有着同样的问题