我使用Runtime.getRuntime().exec
String line = "";
String output = "";
Process p = Runtime.getRuntime().exec(new String[]{"dmidecode | grep UUID:"});
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n').trim();
}
input.close();
我测试了这个并且无法正常工作
String line = "";
String output = "";
Process p = Runtime.getRuntime().exec("dmidecode | grep UUID");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n').trim();
}
input.close();
我在linux机器上遇到下一个错误:
java.io.IOException: Cannot run program "dmidecode | grep UUID:": error no such file or directory
但是我在控制台中测试了命令,我得到了结果!
dmidecode | grep UUID:=> UUID: 564DAF5F-FBF7-5FEE-6BA4-67F0B12D8E0E
如何使用基于Java的Process
获得相同的结果?
答案 0 :(得分:2)
管道运算符|
不会工作,因为这是命令shell的一部分。尝试使用shell来执行命令。您也可以使用ProcessBuilder
以方便
ProcessBuilder builder =
new ProcessBuilder("bash", "-c", "dmidecode | grep UID:");
builder.redirectErrorStream(true);
Process p = builder.start();