Skip to content

Instantly share code, notes, and snippets.

@gkhays
Last active March 18, 2016 21:34
Show Gist options
  • Save gkhays/cfd0988b12a67825d796 to your computer and use it in GitHub Desktop.
Save gkhays/cfd0988b12a67825d796 to your computer and use it in GitHub Desktop.

Run System Commands within Java Applications

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.

import java.io.*;
/**
* @see <a href="http://alvinalexander.com/java/edu/pj/pj010016">Running system commands in Java applications</a>
* /
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
int returnCode = 0;
try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("ps aux"); // Or ps -ef
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// 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);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
returnCode = p.waitFor();
System.out.printf("Command returned %d\n", returnCode);
System.exit(returnCode);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment