Pages

June 4, 2008

Java - Run a System Command and Return Output

Run a system command and return output:
import java.io.*;

public static String cmdExec(String cmdLine) {
    String line;
    String output = "";
    try {
        Process p = Runtime.getRuntime().exec(cmdLine);
        BufferedReader input = new BufferedReader
            (new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            output += (line + '\n');
        }
        input.close();
        }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}
Sample Usage:
public static void main(String[] args) {
    CmdExec cmd = new CmdExec();
    System.out.println(cmd.run("ls -a"));
}

4 comments:

  1. What do your imports look like?

    ReplyDelete
  2. @jonathan:

    oops just added the import.

    ReplyDelete
  3. Thanks! I figured it out, but thought it would be easier for people to just copy/paste and try...

    ReplyDelete
  4. AnonymousJune 22, 2008

    /bow for doing a rrdlib in python

    -the other corey...

    ReplyDelete