我希望能够在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之前从未这样做过,所以任何想法或建议都非常感激。
答案 0 :(得分:2)
您的代码几乎没问题,您只是放错了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);
}
}
我相信这是你想要实现的目标。
答案 1 :(得分:1)
试试这个
public void checkDisks() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec(new String[]{"df","-h"});
int exitValue = p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line=reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("Process exitValue:" + exitValue);
}