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.

Answer from Senthil on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - String[] cmd3 = {"echo", "$HOME"}; String[] env3 = {"HOME=/path/to/custom/home"}; Process process3 = Runtime.getRuntime().exec(cmd3, env3); int exitCode3 = process3.waitFor(); System.out.println("Variant 3 - Exit Code: " + exitCode3); // Variant ...
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;
}
🌐
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); } }
🌐
Java Guides
javaguides.net › 2023 › 09 › java-runtimeexec.html
Java Runtime.exec()
September 27, 2023 - 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) BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // Wait for the process to exit and get the return value int exitValue = process.waitFor(); System.out.println("Process exit value: " + exitValue); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-getruntime-method
Java Runtime getRuntime() Method with Examples - GeeksforGeeks
July 23, 2025 - ... // Java Program to implement ... Getting the runtime object Runtime runtime = Runtime.getRuntime(); // Example 1: Executing System Command try { // Executing a system command to open a web page // (https://www.gfg.com/) Process ...
🌐
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 notepad.exe"); // create a process and execute notepad.exe Process process = Runtime.getRuntime().exec("notepad.exe"); // print another message System.out.println("Notepad should now open."); } catch (Exception ex) { ex.printStackTrace(); } } } Let us compile and run the above program, this will produce the following result − · Executing notepad.exe Notepad should now open. The following example shows the usage of Java Runtime exec() method.
🌐
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.
🌐
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.
🌐
IBM
ibm.com › docs › ssw_ibm_i_74 › rzaha › clcommex.htm
Calling a CL command with java.lang.Runtime.exec()
October 7, 2025 - In this example, the Java class runs a CL command. The CL command uses the Display JVM Jobs (DSPJVMJOB) CL command to display all of the jobs on the system that contain an active Java Virtual Machine.
Find elsewhere
🌐
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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Runtime.html
Runtime (Java Platform SE 8 )
April 21, 2026 - Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
🌐
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).
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - So, we can create the whole command where we want to use pipe and pass it to .exec(): if (IS_WINDOWS) { process = Runtime.getRuntime() .exec(String.format("cmd.exe /c dir %s | findstr \"Desktop\"", homeDirectory)); } else { process = ...
🌐
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.
🌐
More of Less
moreofless.co.uk › system-exec-java-not-working
How to exec external commands in Java with correct parameters
Process process = Runtime.getRuntime().exec("helloworld \"Mickey Mouse\" param2"); int exitCode = process.waitFor(); System.out.println(exitCode);
🌐
IBM
ibm.com › docs › en › i › 7.4.0
Calling another Java program with java.lang.Runtime.exec()
October 7, 2025 - Note: By using the code examples, you agree to the terms of the Code license and disclaimer information. import java.io.*; public class CallHelloPgm { public static void main(String args[]) { Process theProcess = null; BufferedReader inStream = null; System.out.println("CallHelloPgm.main() invoked"); // call the Hello class try { theProcess = Runtime.getRuntime().exec("java QIBMHello"); } catch(IOException e) { System.err.println("Error on exec() method"); e.printStackTrace(); } // read from the called program's standard output stream try { inStream = new BufferedReader( new InputStreamReader( theProcess.getInputStream() )); System.out.println(inStream.readLine()); } catch(IOException e) { System.err.println("Error on inStream.readLine()"); e.printStackTrace(); } } } Copy to clipboard ·