2

I want to be able to make run a system command on Mac OSX from within Java. My code looks like this:

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

This always returns null and an exitValue of 0. Never done this before in Java so any thoughts or suggestions greatly appreciated.

1
  • 0 indicates normal execution of the command "df -h", but why are you trying to read the InputStream from p ? you may want to read from a file instead. Commented Oct 14, 2013 at 9:02

2 Answers 2

3

Your code is almost OK, you just misplaced the 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);
    }
}

I believe it's what you're trying to achieve.

Sign up to request clarification or add additional context in comments.

1 Comment

That'll do for testing purposes. When using in production, I'd advise using StringBuilder.
1

try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.