This gist is based on the blog article Running system commands in Java applications, by Alvin Alexander. Running a command is pretty easy:
Process p = Runtime.getRuntime().exec("ps -ef");
The tricky part is capturing the output:
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
The author has a newer article: Java exec - execute system processes with Java ProcessBuilder and Process (part 1), which as the name suggests, uses ProcessBuilder
. The author also cites Apache Commons Exec, which is used in Apache Ant.