"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > How Can I Execute Command Prompt Commands, Including Directory Changes, in Java?

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

2025-03-26에 게시되었습니다
검색:922

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.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3