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