解
您应该尝试在不同的线程上执行读取和执行.
更好的选择是使用ProcessBuilder,它为您处理“脏”的工作.
try块中的代码可能如下所示:
/* Create the ProcessBuilder */
ProcessBuilder pb = new ProcessBuilder(commandArr);
pb.redirectErrorStream(true);
/* Start the process */
Process proc = pb.start();
System.out.println("Process started !");
/* Read the process's output */
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
/* Clean-up */
proc.destroy();
System.out.println("Process ended !");
问题的原因
根据Java Docs,waitFor():
causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.
因此,您尝试在终止后获取进程的输出流,因此为null.
(对不起,主要修改了答案.)