You are not capturing STDERR, so when errors occur you do not receive them from STDOUT (which you are capturing). Try:

BufferedReader input = new BufferedReader(new InputStreamReader(
               pr.getErrorStream()));
Answer from hkd93 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - String cmd6 = "ls -l"; String[] env6 = {"HOME=/path/to/custom/home"}; File workingDir6 = new File("/path/to/directory"); Process process6 = Runtime.getRuntime().exec(cmd6, env6, workingDir6); int exitCode6 = process6.waitFor(); System.out.p...
🌐
Tutorialspoint
tutorialspoint.com › java › lang › runtime_exec.htm
Java Runtime exec() Method
package com.tutorialspoint; public class RuntimeDemo { public static void main(String[] args) { try { // print a message System.out.println("Executing explorer.exe"); // create a process and execute explorer.exe Process process = Runtime.getRuntime().exec("explorer.exe"); // print another message System.out.println("Windows Explorer should now open."); } catch (Exception ex) { ex.printStackTrace(); } } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Runtime.html
Runtime (Java Platform SE 8 )
April 21, 2026 - Loads the native library specified by the filename argument. The filename argument must be an absolute path name. (for example Runtime.getRuntime().load("/home/avh/lib/libX11.so");).
🌐
GitHub
gist.github.com › f3348e7843994bdd56f0
Java Runtime.getRuntime().exec() Example · GitHub
package api; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Exec { /** * @param args */ public static void main(String[] args) { String result = ""; try { // Execute command String command = "k:\\curl.exe -d login_name=mohwtest -d login_passwd=12345 --insecure https://mohw.cyberhood.net.tw/xml_import.php"; Process child = Runtime.getRuntime().exec(command); DataInputStream in = new DataInputStream( child.getInputStream()); BufferedReader br = new BufferedReader( new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { result +=line; } in.close(); } catch (IOException e) { } System.out.println(result); } } Sign up for free to join this conversation on GitHub.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Runtime.html
Runtime (Java Platform SE 7 )
Loads the specified filename as a dynamic library. The filename argument must be a complete path name, (for example Runtime.getRuntime().load("/home/avh/lib/libX11.so");).
🌐
Coderanch
coderanch.com › t › 419192 › java › Runtime-getRuntime-exec-String-command
Runtime getRuntime() exec(String command) - How does this work? (Java in General forum at Coderanch)
June 16, 2003 - I tried to modify your first example to run telnet, but nothing happened. Mir. ... You can invoke command line program(s) by saying: Runtime rt = Runtime.getRuntime(); String[] cmd = new String[2]; cmd[0] = "cmd /c mkdir " + destDir; rt.exec(cmd[0]); Hope this helps.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-getruntime-method
Java Runtime getRuntime() Method with Examples - GeeksforGeeks
July 23, 2025 - Example 1: Executing System Command Exit Code: 0 Example 2: Retrieving Available Processors Available Processors: 4 Example 3: Querying Total and Free Memory Total Memory (MB): 123 Free Memory (MB): 78 · The Runtime.getRuntime() method provides access to the runtime environment of your Java application.
Top answer
1 of 14
324

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 command
System.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 command
System.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.

2 of 14
88

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;
}
Find elsewhere
🌐
Bureau of Economic Geology
beg.utexas.edu › lmod › agi.servlet › doc › detail › java › lang › Runtime.html
java.lang Class Runtime
Loads the specified filename as a dynamic library. The filename argument must be a complete pathname. From java_g it will automagically insert "_g" before the ".so" (for example Runtime.getRuntime().load("/home/avh/lib/libX11.so");).
🌐
javaspring
javaspring.net › blog › java-runtime-exec
Java Runtime Exec: A Comprehensive Guide — javaspring.net
Here is an example of running a simple Python script that reads user input: import java.io.IOException; import java.io.OutputStream; public class SendInputToProcessExample { public static void main(String[] args) { try { String[] command = {"python", "-c", "print(input())"}; Process process = Runtime.getRuntime().exec(command); // Send input to the process OutputStream outputStream = process.getOutputStream(); String input = "Hello, World!"; outputStream.write(input.getBytes()); outputStream.flush(); outputStream.close(); int exitCode = process.waitFor(); System.out.println("Process exited with code " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
This example will capture the output (from stdio) of an external program. package com.rgagnon.howto; import java.io.*; public class Exec { public static void main(String args[]) { try { String line; Process p = Runtime.getRuntime().exec("cmd /c dir"); BufferedReader bri = new BufferedReader (new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } } } The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be interpreted by the shell.
🌐
Java Guides
javaguides.net › 2023 › 09 › java-runtimeexec.html
Java Runtime.exec()
September 27, 2023 - - The subprocess is not synchronized with the Java application, so you might want to use methods like waitFor() on the Process object to have your Java program wait for the subprocess to finish. - Be cautious while executing arbitrary commands, especially if they are derived from untrusted sources. public class ExecuteCommandExample { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); try { // Using the first syntax: exec(String command) Process process = runtime.exec("ping -c 1 www.google.com"); // Retrieving the input stream (where the command sends its output)
🌐
Coderanch
coderanch.com › t › 564537 › java › Runtime-getRuntime-exec-cmd-work
Runtime getRuntime() exec(cmd[]) - How does this work? (Java in General forum at Coderanch)
January 15, 2012 - If your process's stderr or stdout streams fill up with content, they will lock up your process; this causes problems for a LOT of people when they execute native code through Java. In short, you need to create threads that will read the content from the stdout and stderr streams after you execute the command (rt.exec() line). Read this article and see page 4 for a good example about it (it's the StreamGobbler class).
Top answer
1 of 1
3
  1. Use ProcessBuilder of Runtime#exec, it provides a more configurable solution and encourages the use of String[] or List<String> for the commands and parameters, which solves a bunch of issues, especially when your parameters contain spaces.
  2. Read the Process's InputStream

For example...

try {
    String[] command = {"java.exe", "-?"};
    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(true);
    Process exec = pb.start();

    BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
    String text = null;
    while ((text = br.readLine()) != null) {
        System.out.println(text);
    }

    System.out.println("Process exited with " + exec.waitFor());
} catch (IOException | InterruptedException exp) {
    exp.printStackTrace();
}

Which outputs

Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include:
    -d32      use a 32-bit data model if available
    -d64      use a 64-bit data model if available
    -server   to select the "server" VM
                  The default VM is server.

    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A ; separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose:[class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -no-jre-restrict-search
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions with specified granularity
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions with specified granularity
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                  see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.
Process exited with 0

This assumes that java.exe is within the PATH environment, otherwise you may be required to provide the full path to it (or change the working directory)

🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
When Runtime.exec() won’t | InfoWorld
December 29, 2000 - In our first example, we will attempt to execute the Java compiler (javac.exe): Listing 4.1 BadExecJavac.java · import java.util.*; import java.io.*; public class BadExecJavac { public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("javac"); int exitVal = proc.exitValue(); System.out.println("Process exitValue: " + exitVal); } catch (Throwable t) { t.printStackTrace(); } } } A run of BadExecJavac produces: E:classescomjavaworldjpitfallsarticle2>java BadExecJavac java.lang.IllegalThreadStateException: process has not exited at java.lang.Win32Process.exitValue(Native Method) at BadExecJavac.main(BadExecJavac.java:13) If an external process has not yet completed, the exitValue() method will throw an IllegalThreadStateException; that’s why this program failed.
🌐
IBM
ibm.com › docs › ssw_ibm_i_74 › rzaha › clcommex.htm
Calling a CL command with java.lang.Runtime.exec()
October 7, 2025 - import java.io.*; public class CallCLCom { public static void main(String[] args) { try { Process theProcess = Runtime.getRuntime().exec("system DSPJVMJOB OUTPUT(*PRINT)"); } catch(IOException e) { System.err.println("Error on exec() method"); ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-runtime-class-in-java
Java.lang.Runtime class in Java - GeeksforGeeks
May 6, 2022 - Example 5: Java · // Java program to illustrate halt() // method of Runtime class public class GFG { public static void main(String[] args) { // halt this process Runtime.getRuntime().halt(0); // print a string, just to see if it process is halted System.out.println("Process is still running."); } } Output: From above output it is made clear above program compiled successfully and run. There is no print statement is execute as we have used halt() method which terminates the further execution of operations.
🌐
Tabnine
tabnine.com › home › code library
https://www.tabnine.com/code/java/methods/java.lan...
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.