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:
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