Home >Java >javaTutorial >How Can I Run CMD Commands and Change Directories from within a Java Program?

How Can I Run CMD Commands and Change Directories from within a Java Program?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 08:31:11677browse

How Can I Run CMD Commands and Change Directories from within a Java Program?

Running CMD Commands from Java

As you've discovered, executing CMD commands from within a Java program can be a tricky task. While there are numerous code snippets available online, it can be difficult to comprehend them all.

Let's start by addressing your goal of opening the CMD prompt:

public void excCommand(String new_dir){
    Runtime rt = Runtime.getRuntime();
    try {
        rt.exec(new String[]{"cmd.exe","/c","start"});

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This code successfully opens the CMD prompt. To change to a different directory before running commands, you need to modify the command passed to rt.exec().

For instance, to change to the directory "C:Program FilesFlowella" and then run the "dir" command, use the following code:

ProcessBuilder builder = new ProcessBuilder(
    "cmd.exe", "/c", "cd \"C:\Program Files\Flowella\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();

The cd command is used to change directories, and the && operator ensures that the dir command is only executed if the directory change is successful. The redirectErrorStream(true) method combines the standard output and error streams into a single stream for easier processing.

Finally, reading the standard output of the process allows you to display the directory contents on the console.

The above is the detailed content of How Can I Run CMD Commands and Change Directories from within a Java Program?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn