Alex Rivera | Logout

Collect Linux command output

Asked 2011-06-22T14:10:56.513
14

I am now on a linux machine. I have a Java program which would run some linux command, for example ps, top, list or free -m.

The way to run a command in Java is as follows:

Process p = Runtime.getRuntime().exec("free -m");

How could I collect the output by Java program? I need to process the data in the output.

Edit
Report

1 Answer

6

To collect the output you could do something like

 Process p = Runtime.getRuntime().exec("my terminal command");

  p.waitFor();
  BufferedReader buf = new BufferedReader(new InputStreamReader(
          p.getInputStream()));
  String line = "";
  String output = "";

  while ((line = buf.readLine()) != null) {
    output += line + "\n";
  }

  System.out.println(output);

This would run your script and then collect the output from the script into a variable. The link in Joachim Sauer's answer has additional examples of doing this.

answered 2011-06-22T14:22:07.540

Your Answer