我试图让 Java 执行另一个程序,但它会立即出错,退出代码为 128,并且没有任何内容发送到 stdout 或 stderr。我尝试了一个简单的“java -version”仍然没有运气。当我在 cmd 窗口中运行它时,它运行良好,并且此代码适用于类似配置的其他机器(Windows Server 2003 x64,Java 1.6 update 25)
在命令行上运行时:
C:\Documents and Settings\zugwalt>java -version
输出:
java version "1.6.0_25" Java(TM) SE
Runtime Environment (build1.6.0_25-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.0-b11, mixed mode)
然后我试试这段代码:
try {
List<String> cmd = new LinkedList<String>();
cmd.add("java");
cmd.add("-version");
ProcessBuilder apb = new ProcessBuilder(cmd);
apb.redirectErrorStream(true);
System.out.println("STARTING w00t!");
Process p = apb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
System.out.println("OUTPUT: "+line);
}
System.out.println("EXIT: "+p.exitValue());
System.out.println("WAIT FOR: "+p.waitFor());
} catch (Exception ex) {
System.out.println("CAUGHT: "+ex.getMessage());
ex.printStackTrace();
}
输出是:
STARTING w00t!
EXIT: 128
WAIT FOR: 128