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

CopyBufferedReader 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...
🌐
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.
🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › runtime_exec_envp.htm
Java Runtime exec() Method
package com.tutorialspoint; public class RuntimeDemo { public static void main(String[] args) { try { // create a new array of 1 string String[] cmdArray = new String[1]; // first argument is the program we want to open cmdArray[0] = "calc.exe"; // print a message System.out.println("Executing calc.exe"); // create a process and execute cmdArray and currect environment Process process = Runtime.getRuntime().exec(cmdArray,null); } catch (Exception ex) { ex.printStackTrace(); } } } Let us compile and run the above program, this will produce the following result − · Executing calc.exe · The following example shows the usage of Java Runtime exec() method.
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;
}
🌐
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");).
🌐
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(); } } }
🌐
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 ...
Find elsewhere
🌐
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).
🌐
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");).
🌐
Coalfire
coalfire.com › home › coalfire articles › command injection in java: 80% proven that it is 100% impossible (sometimes)
Command Injection in Java | Coalfire
March 17, 2025 - Update: The zip file is no longer accessible, but you can still see the implications of the JVM using safe "execve" calls here. It shows that the Java String sent to Runtime.getRuntime().exec(command) gets split on ' ', the first resulting String is the executable that gets run and the remaining Strings in the array are passed along as the arguments so even if they contain control characters or other commands those are just sent to the executable as the argv parameters.
🌐
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.
🌐
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): ... 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(); } } }
🌐
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.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › lang › Runtime.html
Runtime (Java SE 21 & JDK 21)
January 20, 2026 - This method is error-prone and should not be used, the corresponding method exec(String[], String[], File) or ProcessBuilder should be used instead. ... Initiates the shutdown sequence of the Java Virtual Machine. ... Returns the amount of free memory in the Java Virtual Machine. ... Runs the garbage collector in the Java Virtual Machine. ... Returns the runtime object associated with the current Java application.
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)