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

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

Susan Sarandon
Release: 2024-12-11 13:13:10
Original
702 people have browsed it

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);
        }
    }
}
Copy after login

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.

The above is the detailed content of How Can I Execute Command Prompt Commands, Including Directory Changes, in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template