I found this in forums.oracle.com

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

You need something like

   String[] command =
    {
        "cmd",
    };
    Process p = Runtime.getRuntime().exec(command);
    new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
    new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
    PrintWriter stdin = new PrintWriter(p.getOutputStream());
    stdin.println("dir c:\\ /A /Q");
    // write any other commands you want here
    stdin.close();
    int returnCode = p.waitFor();
    System.out.println("Return code = " + returnCode);

SyncPipe Class:

class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
      istrm_ = istrm;
      ostrm_ = ostrm;
  }
  public void run() {
      try
      {
          final byte[] buffer = new byte[1024];
          for (int length = 0; (length = istrm_.read(buffer)) != -1; )
          {
              ostrm_.write(buffer, 0, length);
          }
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  }
  private final OutputStream ostrm_;
  private final InputStream istrm_;
}
Answer from Pepe on Stack Overflow
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ lang โ€บ runtime_exec.htm
Java Runtime exec() Method
The Java Runtime exec(String command) method executes the specified string command in a separate process. This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null,
๐ŸŒ
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 - First, weโ€™ll use the .exec() method the Runtime class provides. Then, weโ€™ll learn about ProcessBuilder, which is more customizable. Shell commands are OS-dependent as their behavior differs across systems. So, before we create any Process to run our shell command in, we need to be aware of the operating system on which our JVM is running.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this tutorial, we'll cover how to execute shell commands, bat and sh files in Java. We'll be covering examples for all exec() and ProcessBuilder approaches.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - Process: When you call exec(), it spawns a new native process. This process runs independently of your Java application and allows you to execute system commands.
๐ŸŒ
CodeJava
codejava.net โ€บ java-se โ€บ file-io โ€บ execute-operating-system-commands-using-runtime-exec-methods
How to Execute Operating System Commands in Java
July 27, 2019 - Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.Basically, to execute a system command, pass the command string to the exec() method of the Runtime class.
๐ŸŒ
Real's HowTo
rgagnon.com โ€บ javadetails โ€บ java-0014.html
Execute an external program - Real's Java How-to
String[] cmd = {"/bin/sh", "-c", "ls > hello"}; Runtime.getRuntime().exec(cmd); Since 1.5, the ProcessBuilder class provides more controls overs the process to be started. It's possible to set a starting directory. import java.io.*; import java.util.*; public class CmdProcessBuilder { public static void main(String args[]) throws InterruptedException,IOException { List<String> command = new ArrayList<String>(); command.add(System.getenv("windir") +"\\system32\\"+"tree.com"); command.add("/A"); ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> environ = builder.environme
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands.
Find elsewhere
Top answer
1 of 15
166

One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.

The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:

Copyimport java.io.*;

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
    }
}

Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.

This gives me the following output on my machine:

C:\Users\Luke\StackOverflow>java CmdTest
 Volume in drive C is Windows7
 Volume Serial Number is D8F0-C934

 Directory of C:\Program Files\Microsoft SQL Server

29/07/2011  11:03    <DIR>          .
29/07/2011  11:03    <DIR>          ..
21/01/2011  20:37    <DIR>          100
21/01/2011  20:35    <DIR>          80
21/01/2011  20:35    <DIR>          90
21/01/2011  20:39    <DIR>          MSSQL10_50.SQLEXPRESS
               0 File(s)              0 bytes
               6 Dir(s)  209,496,424,448 bytes free
2 of 15
19

You can try this:-

CopyProcess p = Runtime.getRuntime().exec(command);
๐ŸŒ
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.
๐ŸŒ
ExtraVM
thishosting.rocks โ€บ how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - Runtime.exec() is a simple high-level ... to communicate within its environment. The exec() method is for executing commands directly or running .bat/.sh files....
๐ŸŒ
IBM
ibm.com โ€บ docs โ€บ en โ€บ i โ€บ 7.4.0
Calling another Java program with java.lang.Runtime.exec()
October 7, 2025 - 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(); } } }
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 7 โ€บ docs โ€บ api โ€บ java โ€บ lang โ€บ Runtime.html
Runtime (Java Platform SE 7 )
This is a convenience method. An invocation of the form exec(command, envp, dir) behaves in exactly the same way as the invocation exec(cmdarray, envp, dir), where cmdarray is an array of all the tokens in command.
๐ŸŒ
Alvin Alexander
alvinalexander.com โ€บ java โ€บ java-exec-system-command-pipeline-pipe
Java exec: How to execute a system command pipeline in Java | alvinalexander.com
The only thing I'd like to add here today is that the most important part of this solution was realizing that when you exec a system command from a Java application, you don't actually get a Unix or Linux shell to run your command in. You're really just running the command without a shell wrapper.
๐ŸŒ
Medium
beknazarsuranchiyev.medium.com โ€บ run-terminal-commands-from-java-da4be2b1dc09
Run terminal commands from Java. In this article, we will discuss how toโ€ฆ | by Beknazar | Medium
April 24, 2022 - We work on actual execution with Process instance. For example to get the status code from the process, to get its id, to see the output, to wait, and to kill the process. Thank you for reading, have a wonderful day! Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming OS, File, and File System Working with terminal Welcome to Java Programming Language Variables and Primitives in Java Convert String to numeric data type Input from the terminal in Java Methods with Java
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-execute-native-shell-commands-from-java-program
How to Execute Native Shell Commands from Java Program? - GeeksforGeeks
March 3, 2021 - We use a list to build commands and then execute them using the "start" method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine. ... // Run a simple Windows shell command import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ShellCommandRunner { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); List<String> builderList = new ArrayList<>(); // add the list of comm
๐ŸŒ
Medium
harith-sankalpa.medium.com โ€บ how-to-run-system-commands-from-java-applications-a914223edd24
How To Run System Commands From Java Applications | by Harith Sankalpa | Medium
October 21, 2019 - As soon as the โ€œexecโ€ method is called the input command will be run. exec() method returns a Process object which can be used for the next step. We can directly get the process without creating the Runtime object as follows.
๐ŸŒ
Alvin Alexander
alvinalexander.com โ€บ java โ€บ edu โ€บ pj โ€บ pj010016
Running system commands in Java applications | alvinalexander.com
June 4, 2016 - Executing a system command is relatively simple - once you've seen it done the first time. It involves the use of two Java classes, the Runtime class and the Process class. Basically, you use the exec method of the Runtime class to run the command as a separate process.
๐ŸŒ
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.
๐ŸŒ
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 - Using the java exec() you cannot re-direct stdio as you can from the command line. The command line interpreter (shell) handles I/O redirection. Using the Process object in Java, you need to handle redirection yourself.