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:

import 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
Answer from Luke Woodward on Stack Overflow
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:

import 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:-

Process p = Runtime.getRuntime().exec(command);
Discussions

process - How to execute cmd command in Java class? - Stack Overflow
I want to call cmd command in java code. More on stackoverflow.com
🌐 stackoverflow.com
How to execute cmd commands through java - Stack Overflow
I have jar file(selenium-server-standalone-2.44.0.jar) kept at c:\ drive. I need to navigate to C drive and execute below command through java java -jar selenium-server-standalone-2.44.0.jar -ro... More on stackoverflow.com
🌐 stackoverflow.com
November 1, 2016
Execute commands in cmd using Java - Stack Overflow
I am using the following code to run the cmd.exe and the cmd window appears which is fine. More on stackoverflow.com
🌐 stackoverflow.com
Running Command Line in Java - Stack Overflow
Actually, I think you only need the "cmd /c", if you are wanting to run a windows command, like "copy". Apologies for the confusion. 2015-12-15T23:56:32.677Z+00:00 ... this doesn't print the whole output for me. executing "ls" prints different amounts of the directory contents each time. this works best for me: alvinalexander.com/java... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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.
🌐
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 - For example, the following statements execute a Windows command to list content of the Program Files directory: String commandArray[] = {"cmd", "/c", "dir", "C:\\Program Files"}; Process process = Runtime.getRuntime().exec(commandArray);For other exec() methods, consult the relevant Javadoc which is listed below.
🌐
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 - In this article, we’ll learn how to execute a shell command from Java applications. 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. Additionally, on Windows, the shell is commonly referred to as cmd.exe.
🌐
JavaMadeSoEasy
javamadesoeasy.com › 2015 › 08 › execute-cmd-commands-through-java.html
JavaMadeSoEasy.com (JMSE): Execute CMD commands through java program
java allows us to execute CMD commands through programs In CMD, typing below command will open the file c:/myFile.txt > C:\> c:\m...
Find elsewhere
🌐
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 - In this article, we will discuss how to run terminal commands from Java code. We can execute specific commands from the terminal to execute processes in an operating system.
🌐
javaspring
javaspring.net › blog › how-to-execute-cmd-commands-via-java
How to Execute CMD Commands via Java: Troubleshooting When `cd` and `dir` Commands Fail to Run — javaspring.net
Even if you could run cd, its effect would be limited to the subprocess (the shell session), not the Java process or subsequent commands. To run cd, you must invoke the cmd.exe shell and pass cd as an argument using cmd /c (the /c flag tells ...
🌐
TutorialsPoint
tutorialspoint.com › article › java-program-to-open-the-command-prompt-and-insert-commands
Java Program to open the Command Prompt and Insert commands
June 24, 2024 - The details of how to run these programs by using javac and java commands are given in detail in this article, in the output section. Step 1 ? Using Java code open the CMD window. Step 2 ? Select the command to be executed.
🌐
Netjstech
netjstech.com › 2016 › 10 › running-dos-windows-commands-from-java.html
Running Dos/Windows Commands From Java Program | Tech Tutorials
Using this exec() method dos or windows commands can be executed from Java. Runtime.getRunTime().exec to run dos/windows commands in Java example · import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RunningCommand { public static void ...
🌐
CodingTechRoom
codingtechroom.com › question › execute-cmd-commands-java
How to Execute Command Prompt (cmd.exe) Commands from Java? - CodingTechRoom
Executing Command Prompt commands from a Java application can be efficiently achieved using the Java ProcessBuilder class. This allows you to run system-level commands directly from your Java programs, enabling greater control over external processes and resources.
🌐
javathinking
javathinking.com › blog › how-to-open-the-command-prompt-and-insert-commands-using-java
How to Open Command Prompt/Terminal and Execute Commands in Java Using Runtime.exec() — javathinking.com
In essence, Runtime.exec() acts as a bridge between your Java application and the OS shell, enabling execution of terminal/command prompt commands. Runtime.exec() has several overloaded variants to handle different use cases: The most commonly used variants are exec(String command) and exec(String[] cmdarray).
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-open-command-prompt-insert-commands
Java Program to Open the Command Prompt and Insert Commands - GeeksforGeeks
April 22, 2025 - To execute the commands inside the command prompt we can use Runtime.exec() method. We can perform various commands such as dir, which is used to list all directories and the ping, which is used to test the ability of the source computer to ...
🌐
Princeton CS
introcs.cs.princeton.edu › java › 15inout › windows-cmd.html
Java and the Windows Command Prompt
First, be sure that HelloWorld.class is now in the current directory. Be sure to type java HelloWorld without a trailing .class or .java. Check that the command "java -version" works. Now try to execute with "java -cp . HelloWorld". If this works, you need to edit your classpath.
🌐
Quora
quora.com › Can-we-open-a-command-prompt-using-Java-program
Can we open a command prompt using Java program? - Quora
They’re always with me, I can ... search instantly, and it’s easy to read at night without a lamp. Physical books still win for comfort and vibe—especially for novels I really want to slow down with or keep on a shelf. If I’m traveling or reading a lot, eBooks. If it’s a “sit and enjoy” book, physical. ... You can use Runtime to open command line using Java. For example when making my project, I wanted to open cmd from my program and execute command javac ...
Top answer
1 of 8
216
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

2 of 8
61

You can also watch the output like this:

final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

new Thread(new Runnable() {
    public void run() {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;

        try {
            while ((line = input.readLine()) != null)
                System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

p.waitFor();

And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.

EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:

String[] command = new String[] {
        "choice",
        "/C",
        "YN",
        "/M",
        "\"Press Y if you're cool\""
};
String inputLine = "Y";

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

writer.write(inputLine);
writer.newLine();
writer.close();

String line;

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:

Press Y if you're cool [Y,N]?Y