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
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - String cmd6 = "ls -l"; String[] ... Exit Code: 0 · The exec() function in Java's Runtime class provides various options for communicating with the operating system....
Discussions

java - Safe usage of Runtime.getRuntime.exec(String[]) - Information Security Stack Exchange
I was reviewing code of an application that uses the following piece of Java code and wanted to know if the the use of exec() was susceptible to command injection. public class FindFileInDir { ... More on security.stackexchange.com
🌐 security.stackexchange.com
April 5, 2020
Runtime.getRuntime().exec leaving processes running?
runtime.getRuntime().exec returns a Process object. If a process does not close on its own, you can close that process by calling destroy () More on reddit.com
🌐 r/javahelp
5
2
April 14, 2016
Runtime.getRuntime().exec()
How can I exec a program and have the output displayed in the textarea that I've created while running? The code work OK if I pass it simple commands like "dir" etc. but hangs when I start my application. The application I'm running is a java server process which does not return(end) unless ... More on experts-exchange.com
🌐 experts-exchange.com
November 12, 2000
unix - Java :Kill process runned by Runtime.getRuntime().exec() - Stack Overflow
As of Java 9, you can just call proc.pid() to get the pid. 2020-12-02T17:58:01.063Z+00:00 ... Save this answer. ... Show activity on this post. You can get pid with reflection in unix (I know it is a bad idea :)) and call kill; Process proc = Runtime.getRuntime().exec( new String[] ... More on stackoverflow.com
🌐 stackoverflow.com
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;
}
🌐
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 - The key thing to remember when using Runtime.exec() is you must consume everything from the child process' input stream. [ June 16, 2003: Message edited by: Michael Morris ] Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher ... Well let me rephrase my question. How do you run an external windows command line program from a java ...
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-getruntime-method
Java Runtime getRuntime() Method with Examples - GeeksforGeeks
July 23, 2025 - The Runtime.getRuntime() method is a static method that retrieves the runtime object for the current Java application. This object allows you to access various aspects of the application's runtime environment, such as executing system commands, ...
🌐
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 - ... 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.
Find elsewhere
🌐
Code-white
code-white.com › blog › 2015-03-sh-or-getting-shell-environment-from
CODE WHITE | $@|sh – Or: Getting a shell environment from Runtime.exec
March 9, 2015 - Well, the reason for that is that the command passed to Runtime.exec is not executed by a shell. Instead, if you dig down though the Java source code, you’ll end up in the UNIXProcess class, which reveals that calling Runtime.exec results in a fork and exec call on Unix platforms.
🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
When Runtime.exec() won’t | InfoWorld
December 29, 2000 - That makes sense, since javac expects us to follow the program with the source code file to compile. Thus, to circumvent the second pitfall — hanging forever in Runtime.exec() — if the program you launch produces output or expects input, ensure that you process the input and output streams.
🌐
Reddit
reddit.com › r/javahelp › runtime.getruntime().exec leaving processes running?
r/javahelp on Reddit: Runtime.getRuntime().exec leaving processes running?
April 14, 2016 -

Hello all, I've been looking for an answer on this but can't find anything specific. I have an application that is running quite a few runtime.getRuntime().exec processes independently. This is done to run things from the command prompt like ping, WMI commands, etc. and also runs some powershell commands and runs some scripts. I have noticed that after running a few, I can go into task manager and see quite a few powershell and cmd applications open. Is this not closing? I'm pretty new to the idea of garbage collection, but I thought Java took care of that by itself? Do I need to run something to close these once the process has finished running? Thank you for your help!

🌐
Experts Exchange
experts-exchange.com › questions › 11833678 › Runtime-getRuntime-exec.html
Solved: Runtime.getRuntime().exec() - Java
November 12, 2000 - It should work as long as you don't do any quoting weirdness. I mean, something like this _won't_ work: java ExecService "cmd /C" dir If you feel it is worth points -- a might big IF -- you can choose to post another question or not. Let me know if you do so I can go look for it.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › runtime_exec_command_dir.htm
Java Runtime exec() Method
The Java Runtime exec(String command, String[] envp, File dir) method executes the specified string command in a separate process with the specified environment and working directory.
🌐
IBM
ibm.com › docs › fr › i › 7.5.0
IBM Documentation
Use the java.lang.Runtime.exec() method to call programs or commands from within your Java program. Using java.lang.Runtime.exec() method creates one or more additional thread-enabled jobs. The additional jobs process the command string that you pass on the method.
🌐
IBM
ibm.com › docs › de › i › 7.5.0
Beispiel: Anderes Java-Programm mit java.lang.Runtime. ...
This example shows how to call another Java program with java.lang.Runtime.exec(). This class calls the Hello program that is shipped as part of the IBM Developer Kit for Java. When the Hello class writes to System.out, this program gets a handle to the stream and can read from it.
🌐
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 › fr › i › 7.5.0
appel d'un autre programme Java avec java.lang.Runtime. ...
This example shows how to call another Java program with java.lang.Runtime.exec(). This class calls the Hello program that is shipped as part of the IBM Developer Kit for Java. When the Hello class writes to System.out, this program gets a handle to the stream and can read from it.
🌐
Oracle
docs.oracle.com › en › java › javase › 22 › docs › api › java.base › java › lang › Runtime.html
Runtime (Java SE 22 & JDK 22)
July 16, 2024 - ... 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.