簡體   English   中英

在Mac上用Java執行系統命令

[英]Execute System Commands in Java on Mac

我希望能夠在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);
    }
}

我相信這是你想要實現的目標。

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM