问题描述
我有一个简单的程序,它使用echo
运行ProcessBuilder
命令,该程序在我的Linux机器上运行良好,但是在Windows上运行时会抛出IOException
。 / p>
这是我程序的简化版本。它使用echo
和hello
作为ProcessBuilder
的参数,然后将输出保存到字符串中并打印输出。在Linux中,输出为hello
,在Windows中为IOException
。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestPB {
public static void main(String[] args) throws InterruptedException {
ProcessBuilder pb = new ProcessBuilder("echo","hello");
try {
Process process = pb.start();
BufferedReader readProcessOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
String line = "";
while ( (line = readProcessOutput.readLine()) != null) {
output += line;
output += System.getProperty("line.separator");
}
process.waitFor();
if(output.length() > 0) {
System.out.println(output.substring(0,output.length() -1));
} else {
System.out.println("No result");
}
} catch (IOException io) {
System.out.println("IOException thrown");
}
}
}
有人知道为什么这在Windows中不起作用吗?
解决方法
echo
不是Windows上的程序,它是内部shell命令 * ,因此您需要调用命令行解释器:
ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","echo","hello");
*)参考:Wikipedia