Java Runtime.getRuntime(): getting output from executing a command line program Java Runtime.getRuntime(): getting output from executing a command line program java java

Java Runtime.getRuntime(): getting output from executing a command line program


Here is the way to go:

Runtime rt = Runtime.getRuntime();String[] commands = {"system.exe", "-get t"};Process proc = rt.exec(commands);BufferedReader stdInput = new BufferedReader(new      InputStreamReader(proc.getInputStream()));BufferedReader stdError = new BufferedReader(new      InputStreamReader(proc.getErrorStream()));// Read the output from the commandSystem.out.println("Here is the standard output of the command:\n");String s = null;while ((s = stdInput.readLine()) != null) {    System.out.println(s);}// Read any errors from the attempted commandSystem.out.println("Here is the standard error of the command (if any):\n");while ((s = stdError.readLine()) != null) {    System.out.println(s);}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.


A quicker way is this:

public static String execCmd(String cmd) throws java.io.IOException {    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");    return s.hasNext() ? s.next() : "";}

Which is basically a condensed version of this:

public static String execCmd(String cmd) throws java.io.IOException {    Process proc = Runtime.getRuntime().exec(cmd);    java.io.InputStream is = proc.getInputStream();    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");    String val = "";    if (s.hasNext()) {        val = s.next();    }    else {        val = "";    }    return val;}

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

public static String execCmd(String cmd) {    String result = null;    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {        result = s.hasNext() ? s.next() : null;    } catch (IOException e) {        e.printStackTrace();    }    return result;}


If use are already have Apache commons-io available on the classpath, you may use:

Process p = new ProcessBuilder("cat", "/etc/something").start();String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());