"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Execute Command Prompt Commands, Including Directory Changes, in Java?

How Can I Execute Command Prompt Commands, Including Directory Changes, in Java?

Posted on 2025-03-25
Browse:231

How Can I Execute Command Prompt Commands, Including Directory Changes, in Java?

Execute Command Prompt Commands in Java

Problem:

Running command prompt commands through Java can be challenging. Although you may find code snippets that open the command prompt, they often lack the ability to change directories and execute additional commands.

Solution:

To run command prompt commands and change directories using Java, utilize a ProcessBuilder. This approach allows you to:

  • Start a process and redirect its standard error to its standard output.
  • Change directory and execute commands in a single command line.

Code Example:

import java.io.*;

public class CmdRunner {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\Flowella\" && dir");
        builder.redirectErrorStream(true);
        Process p = builder.start();

        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = r.readLine()) != null) {
            System.out.println(line);
        }
    }
}

This code:

  • Utilizes a ProcessBuilder to run the "cd" and "dir" commands.
  • Redirects the process's standard error into its standard output for a single read stream.
  • Prints the output to the console.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3