2

我希望能够从 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 和 0 的 exitValue。以前从未在 Java 中这样做过,因此非常感谢任何想法或建议。

4

2 回答 2

3

你的代码几乎没问题,你只是放错了 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);
    }
}

我相信这是你想要达到的目标。

于 2013-10-14T09:04:19.463 回答
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);
}
于 2013-10-14T09:09:22.323 回答