【问题标题】:Execute System Commands in Java on Mac在 Mac 上用 Java 执行系统命令
【发布时间】:2013-10-21 19:27:19
【问题描述】:

我希望能够从 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 中这样做过,因此非常感谢任何想法或建议。

【问题讨论】:

  • 0 表示正常执行命令“df -h”,但是为什么要从 p 读取 InputStream 呢?您可能想改为从文件中读取。

标签: java macos terminal command


【解决方案1】:

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

我相信这就是您想要实现的目标。

【讨论】:

  • 这将用于测试目的。在生产中使用时,我建议使用 StringBuilder。
【解决方案2】:

试试这个

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2021-09-07
    • 2010-10-21
    • 2011-03-12
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多