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
Answer from Luke Woodward on Stack Overflow
🌐
Florida State University
cs.fsu.edu › ~myers › cop3252 › howto › cmdline.html
Compiling on the Command line with Java SDK
It will not be as good when we get to GUI applications (although can be done through tunnelling) Select "Start", then "Run", then type "cmd", to open a command prompt · Use "cd" command to change directories (similar to unix command) Use "dir" to see a directory listing · Use javac and java ...
🌐
Princeton CS
introcs.cs.princeton.edu › java › 15inout › windows-cmd.html
Java and the Windows Command Prompt
This document instructs you on how to use the Windows Command Prompt with Java.
🌐
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.
🌐
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 - Python TechnologiesDatabasesComputer ... QualityManagement Tutorials View All Categories ... This article uses various approaches for selecting the commands inserted in the opened command window through the Java code. The command window is opened by using ?cmd?....
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);
🌐
KaaShiv InfoTech
kaashivinfotech.com › home › how to run a java program in cmd: step-by-step guide for beginners
How to Run a Java Program in CMD – Easy Step-by-Step
August 9, 2025 - Learn how to run a Java program in CMD with simple steps. Compile, execute, and troubleshoot Java code directly from the command line.
🌐
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 - 1. Type ″cmd″ into Windows search. 2. Right-click Command prompt. 3. Click Run as administrator. 4. Type ″cd \path\to\java\program″. 5. Press Enter. 6. Type ″javac -filename.java″. 7. Press Enter. 8. Type ″java filename.java″. 9.
Find elsewhere
🌐
Jack's blog
jacknodes.hashnode.dev › java-programming-in-cmd-everything-you-need-to-get-started
Java Programming in Cmd: Everything You Need to Get Started
September 16, 2023 - In this article, we'll show you how to set up a Java dev environment using nothing but CMD, how to compile your first Java program, and how to run it. By the end, you'll be writing, compiling and executing Java code like a pro using only your ...
🌐
CodeJava
codejava.net › java-core › tools › examples-of-using-java-command
java command examples
August 4, 2019 - [Master REST API Development and Java and Spring Boot] In this Java tools tutorial, I will guide you how to use the java command provided in JDK (Java Development Kit) to execute Java programs.Table of content:
🌐
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 - It is done by passing "cmd" command to exec() method. ... // Java program to illustrate // open cmd prompt class Geeks { public static void main(String[] args) { try { // Just one line and you are done !
Top answer
1 of 13
274

Source: javaindos.

Let's say your file is in C:\mywork\

Run Command Prompt

CopyC:\> cd \mywork

This makes C:\mywork the current directory.

CopyC:\mywork> dir

This displays the directory contents. You should see filenamehere.java among the files.

CopyC:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin

This tells the system where to find JDK programs.

CopyC:\mywork> javac filenamehere.java

This runs javac.exe, the compiler. You should see nothing but the next system prompt...

CopyC:\mywork> dir

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

CopyC:\mywork> java filenamehere

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

2 of 13
121

To complete the answer :

  1. The Java File

    CopyTheJavaFile.java
    
  2. Compile the Java File to a *.class file

    Copyjavac TheJavaFile.java
    
    • This will create a TheJavaFile.class file
  3. Execution of the Java File

    Copyjava TheJavaFile
    
  4. Creation of an executable *.jar file

    • You've got two options here -

      1. With an external manifest file :

        • Create the manifest file say - MANIFEST.mf

        • The MANIFEST file is nothing but an explicit entry of the Main Class

        • jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class

      2. Executable by Entry Point:

        • jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
  5. To run the Jar File

    Copyjava -jar TheJavaFile.jar
    
🌐
W3Schools
w3schools.com › java › java_getstarted.asp
Java Getting Started
This editor will be used in the entire tutorial to demonstrate the different aspects of Java. 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...
🌐
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 - Quick guide to how to two ways of running a shell command in Java, both on Windows as well as on UNIX.
🌐
Codemia
codemia.io › home › knowledge hub › how do i run a java program from the command line on windows?
How do I run a Java program from the command line on Windows? | Codemia
January 27, 2025 - Running Java programs from the command line on Windows involves several steps that provide a deep understanding of how Java executes programs and how the operating system interacts with Java. This article will take you through detailed steps from writing a simple Java program, compiling it, and finally running it on a Windows command prompt.
🌐
Software Testing Material
softwaretestingmaterial.com › home › selenium › how to run a java program using command prompt
How To Run A Java Program Using Command Prompt
June 11, 2025 - Save your file as HelloTesters.java in C:\SoftwareTestingMaterial. Step iii: Open command prompt · Open Command Prompt (Open Run (Windows+R) and type cmd) Step iv: Run the created Java program using command prompt · Follow the below steps: C:\Users\Admin> cd\ C:\> cd SoftwareTestingMaterial ·
🌐
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 - 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.