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
๐ŸŒ
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 are going to discuss ProcessBuilder.java and Process.java files. Ok, letโ€™s see one code that can execute commands from the terminal: The above code executes ls commands to list files and directories on my desktop. You can modify the path of the file to point to your desktop or any folder and try running other commands.
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);
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ java-for-programmers-java-and-the-command-line
Java and the Command Line | Codecademy
This version of Java, the version that is used simply to run programs, is called the Java Runtime Environment, and essentially takes the compiled Java byte code and allows those generic files to be run specifically on your type of computer. This is one of the core principles that has allowed Java to become as popular as it has. As a developer though, you need the Java Development Kit, or JDK, which allows you access to the classes and interfaces of the core Java language that you use here on Codecademy such as System.out.println(). The current version of Java we have here at Codecademy can be found by typing the command java --version into a terminal when you are doing a lesson.
๐ŸŒ
Visual Studio Code
code.visualstudio.com โ€บ docs โ€บ java โ€บ java-tutorial
Getting Started with Java in VS Code
November 3, 2021 - VS Code also provides IntelliSense ... To run and debug Java code, set a breakpoint, then either press F5 on your keyboard or use the Run > Start Debugging menu item....
๐ŸŒ
Oracle
java.com โ€บ en โ€บ download โ€บ manual.jsp
Download Java
This download is for end users who need Java for running applications on desktops or laptops. Java 8 integrates with your operating system to run separately installed Java applications.
๐ŸŒ
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.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ how to run java program?
How to Run Java Program? - Scaler Topics
March 22, 2024 - 2: The java command executes Java bytecodes. It processes bytecode as input, executes it, and produces the output. This guide highlights how to run Java program, starting from creating the Java file in Notepad to compiling and executing it.
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_getstarted.asp
Java Getting Started
However, if you want to run Java on your own computer, follow the instructions below. Some PCs might have Java already installed. To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):
๐ŸŒ
Princeton CS
introcs.cs.princeton.edu โ€บ java โ€บ windows โ€บ manual.php
Hello World in Java on Windows (manual instructions)
Prepend C:\Program Files\Java\jdk1.7.0_67\bin; to the beginning of the PATH variable. Depending on which version of Java you downloaded, the jdk1.7.0_67 part might be different. Click OK three times. Launch the Command Prompt via All Programs -> Accessories -> Command Prompt.
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ executing-java-code-from-the-command-line-d6a3c09bb565
Executing Java Code from the Command Line | Medium
March 9, 2025 - Learn how to compile and run Java programs from the command line using javac and java, manage classpaths, and understand how the JVM processes bytecode.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 106036 โ€บ ide โ€บ java-run-command-Eclipse
java run command in Eclipse (IDEs and Version Control forum at Coderanch)
Sometimes there will only be the main thread. In my debug perspective window it is top-left. I have two tabs there, one says Debug, the other Servers. When I click on the Debug on, I see the Threads of the last run application. There I click on the "terminated", which then shows the java(w) command.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-run-a-java-program
How to run a java program
February 19, 2024 - Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type 'java MyFirstJavaProgram' to run your program.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - Quick guide to how to two ways of running a shell command in Java, both on Windows as well as on UNIX.
๐ŸŒ
OneCompiler
onecompiler.com โ€บ java
Java Online Compiler
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your name: "); String inp = input.next(); System.out.println("Hello, " + inp); } } OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster.
๐ŸŒ
Oracle
docs.oracle.com โ€บ en โ€บ java โ€บ javase โ€บ 21 โ€บ docs โ€บ specs โ€บ man โ€บ java.html
The java Command
January 20, 2026 - Windows: The javaw command is identical to java, except that with javaw there's no associated console window. Use javaw when you don't want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error information if a launch fails. To launch a class declared in a source file, run the java launcher in source-file mode.
๐ŸŒ
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 - 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.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-execute-and-run-java-code
How to Execute and Run Java Code from the Terminal
March 10, 2022 - To compile a Java code/program, we get the class file. Then we need to execute/run the class file. We need to use the command javac file_name_with_the_extension. For example, as I want to compile my Main.java, I will use the command javac Main.java.
๐ŸŒ
Wikihow
wikihow.com โ€บ computers and electronics โ€บ software โ€บ programming โ€บ java โ€บ how to compile and run a java program using command prompt
How to Compile and Run a Java Program Using Command Prompt
September 28, 2025 - At the command prompt, type "cd" followed by the path your Java program is saved to, then press "Enter." Type "javac [filename] and press "Enter" to compile the program. Type "java [filename]" and press "Enter" to run the Java program after ...
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 562022 โ€บ java โ€บ Running-Java-Programs-command-prompt
Running Java Programs from the command prompt (Beginning Java forum at Coderanch)
December 17, 2011 - To run it. "java Hello" ... Struggled a long time with the same issue yesterday, also on Windows XP. Although I don't really know what I am talking about, here are some suggestions: First, go to the file (Hello.java) and right click it. If this gives you the option of a command prompt, open the command prompt and input javac Hello.java This will create a class file in the same folder.