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 - 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");).
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - String[] cmd2 = {"ls", "-l", "/path/to/directory"}; Process process2 = Runtime.getRuntime().exec(cmd2); int exitCode2 = process2.waitFor(); System.out.println("Variant 2 - Exit Code: " + exitCode2); // Variant 3: exec(String[] cmdarray, String[] envp) // This variant executes the "echo $HOME" command with a custom environment variable.
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
process - How to get java getRuntime().exec() to run a command-line program with arguments? - Stack Overflow
Copypublic class Main { public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); String cmdString = "cmd /c dir"; System.out.println(cmdString); Process pr = rt.exec(cmdString); BufferedReader input = new BufferedReader(new InputStreamReader( pr.getInputStream())); ... More on stackoverflow.com
🌐 stackoverflow.com
Runtime.getRuntime().exec()
Find answers to Runtime.getRuntime().exec() from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
November 12, 2000
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 › 672077 › java › read-output-Runtime-getRuntime-exec
Trying to read the output of a Runtime.getRuntime().exec cmd process. (Java in General forum at Coderanch)
October 27, 2016 - That looks too complicated for us who are only beginning so I shall move you. Have you read the classic article by Michael Daconta? Don't go anywhere near Runtime.exec() until you have. If you use the old‑fashioned way to run Processes, rather than combining streams with a ProcessBuilder, you need two additional threads.
🌐
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!

🌐
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.
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 - 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.
🌐
Experts Exchange
experts-exchange.com › questions › 11833678 › Runtime-getRuntime-exec.html
Solved: Runtime.getRuntime().exec() | Experts Exchange
November 12, 2000 - nEvent A) { kill(); } }); } public void kill() { if (proc != null) { proc.destroy(); proc = null; } if (stdout != null) { stdout.stop(); stdout = null; } if (stderr != null) { stderr.stop(); stderr = null; } if (waiter != null) { waiter.interrupt(); waiter = null; } } public void exec(String[] cmd) { try { // start the external process proc = Runtime.getRuntime().exec(
🌐
Android Developers
developer.android.com › api reference › runtime
Runtime | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
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 ... the garbage collector in the Java Virtual Machine. static Runtime · getRuntime() Returns the runtime object associated with the current Java application....
🌐
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. This is a convenience 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)
This just runs the dir command, captures its ouput and copies it to the programs stdout. Not very exciting but it shows the basic parts to use Runtime.exec().
🌐
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");).
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › x › xTdGBQ
IDS07-J. Sanitize untrusted data passed to the Runtime.exec() method | CERT Secure Coding
It is implemented using Runtime.exec() to invoke the Windows dir command. Non-compliant code · Copy to clipboard · Toggle fullscreen · class DirList { public static void main(String[] args) throws Exception { String dir = System.getProperty("dir"); Runtime rt = Runtime.getRuntime(); Process ...
🌐
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 - 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). As for how you set up the cmdlinux[], I'm not sure if the redirect (<) will cause you trouble in there or not.
🌐
CSDN
blog.csdn.net › chuyouyinghe › article › details › 130504262
Runtime.getRuntime().exec学习和应用,java代码执行命令_runtime.getruntime().exec用法-CSDN博客
May 5, 2023 - javap -l xxx > output.txt 这时要用exec(String[] cmdArray)。如例: · Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c", "javap -l xxx > output.txt"}); 关于返回结果类型:Process,它有几个方法: 1.destroy():杀掉子进程 2.exitValue():返回子进程的出口值,值 0 表示正常终止 3.getErrorStream():获取子进程的错误流 4.getInputStream():获取子进程的输入流 5.getOutputStream():获取子进程的输出流 6.waitFor():导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。如果已终止该子进程,此方法立即返回。如果没有终止该子进程,调用的线程将被阻塞,直到退出子进程,根据惯例,0 表示正常终止 ·
🌐
Reddit
reddit.com › r/learnjava › how do i execute command prompt commands in java 21.0.2
r/learnjava on Reddit: How do I execute Command Prompt commands in Java 21.0.2
May 18, 2024 -

I tried using the following function:

Runtime.getRuntime().exec("DIR")

but it doesn't get executed and my IDE always shows the following warning:

The method exec(String) from the type Runtime is deprecated since version 18Java(67110270)

Top answer
1 of 3
3
When something is marked as deprecated it is always helpful to check out the documentation. Usually it tells you why it was deprecated but also what method to use instead. Deprecated. This method is error-prone and should not be used, the corresponding method exec(String[]) or ProcessBuilder should be used instead. The command string is broken into tokens using only whitespace characters. For an argument with an embedded space, such as a filename, this can cause problems as the token does not include the full filename. So you can either use exec(String[]) or preferably ProcessBuilder . Then, you have to actually pass the following command: ["cmd", "/c", "DIR"] because "DIR" is not a real program, but a command of the windows command prompt. But even then, it will probably still look like your program doesn't work because you won't see any output. To fix this you have to either manually read the output using Process.getInputStream() , or you can simply do var process = new ProcessBuilder("cmd", "/c", "DIR") .redirectOutput(ProcessBuilder.Redirect.INHERIT) .start(); which will redirect output to your Java's program stdout. You may need to add process.waitFor(); To make sure your main thread does not exit before your process has finished.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
IBM
ibm.com › docs › he › ssw_ibm_i_74 › rzaha › javalang.htm
Using java.lang.Runtime.exec()
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.