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