Executing Command Line Commands with Java
When attempting to execute command line arguments using Java, it is crucial to understand the nuances of different operating systems. This article aims to address a specific issue faced by Windows users when trying to execute CMD commands via Java.
The example provided in the question demonstrates an attempt to execute the "cd" and "dir" commands through the command line using Java. However, this method does not yield the expected results. To overcome this, an alternative approach is necessary.
The solution lies in constructing a Command Prompt (CMD) process and interactively communicating with it through input and output streams. This allows for the seamless execution of multiple commands within a single process, as seen in the following code:
String[] command = {"cmd"}; Process p = Runtime.getRuntime().exec(command); // Thread to handle error stream new Thread(new SyncPipe(p.getErrorStream(), System.err)).start(); // Thread to handle input stream new Thread(new SyncPipe(p.getInputStream(), System.out)).start(); // PrintWriter to write to the output stream PrintWriter stdin = new PrintWriter(p.getOutputStream()); // Write the "dir" command stdin.println("dir c:\ /A /Q"); // Close the stdin stream stdin.close(); // Wait for the process to complete int returnCode = p.waitFor(); // Print the return code System.out.println("Return code = " + returnCode);
This approach allows for the execution of multiple commands within the CMD process, providing a more efficient and versatile way of interacting with the command line from Java.
The above is the detailed content of How Can I Execute Multiple CMD Commands from Java?. For more information, please follow other related articles on the PHP Chinese website!