Running CMD Commands from Java
As you've discovered, executing CMD commands from within a Java program can be a tricky task. While there are numerous code snippets available online, it can be difficult to comprehend them all.
Let's start by addressing your goal of opening the CMD prompt:
public void excCommand(String new_dir){ Runtime rt = Runtime.getRuntime(); try { rt.exec(new String[]{"cmd.exe","/c","start"}); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
This code successfully opens the CMD prompt. To change to a different directory before running commands, you need to modify the command passed to rt.exec().
For instance, to change to the directory "C:Program FilesFlowella" and then run the "dir" command, use the following code:
ProcessBuilder builder = new ProcessBuilder( "cmd.exe", "/c", "cd \"C:\Program Files\Flowella\" && dir"); builder.redirectErrorStream(true); Process p = builder.start();
The cd command is used to change directories, and the && operator ensures that the dir command is only executed if the directory change is successful. The redirectErrorStream(true) method combines the standard output and error streams into a single stream for easier processing.
Finally, reading the standard output of the process allows you to display the directory contents on the console.
The above is the detailed content of How Can I Run CMD Commands and Change Directories from within a Java Program?. For more information, please follow other related articles on the PHP Chinese website!