我希望能够从 Java 中在 Mac OSX 上运行系统命令。我的代码如下所示:
public void checkDisks() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("df -h");
int exitValue = p.waitFor();
System.out.println("Process exitValue:" + exitValue);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
}
System.out.println(line);
}
这总是返回 null 且 exitValue 为 0。以前从未在 Java 中这样做过,因此非常感谢任何想法或建议。
最佳答案
你的代码几乎没问题,你只是放错了 println
public void checkDisks() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("df -h");
int exitValue = p.waitFor();
System.out.println("Process exitValue:" + exitValue);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
System.out.println(line);
}
}
我相信这就是您想要实现的目标。
关于java - 在 Mac 上用 Java 执行系统命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356712/