Home > Java > javaTutorial > How to Properly Execute Multiple Command-Line Commands in Java?

How to Properly Execute Multiple Command-Line Commands in Java?

Barbara Streisand
Release: 2024-11-30 21:33:15
Original
725 people have browsed it

How to Properly Execute Multiple Command-Line Commands in Java?

How to Execute Command Line Arguments Via Java

Question:

How do you execute command line arguments through Java? For example, consider the following code:

// Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);

// Get output stream to write from it
OutputStream out = child.getOutputStream();

out.write("cd C:/ /r/n".getBytes());
out.flush();
out.write("dir /r/n".getBytes());
out.close();
Copy after login

This code opens the command line but doesn't execute the "cd" or "dir" commands.

Answer:

To reuse a single process for multiple commands in Windows, follow these steps:

  1. Create a String array with the command name, in this case, "cmd".
  2. Execute the command using Runtime.getRuntime().exec(command).
  3. Start threads to handle error and output streams.
  4. Open a PrintWriter on the output stream.
  5. Write the desired commands to the PrintWriter.
  6. Close the PrintWriter.
  7. Wait for the process to complete with p.waitFor().

Here's an example:

String[] command = {"cmd"};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\ /A /Q");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
Copy after login

SyncPipe Class:

class SyncPipe implements Runnable {
    public SyncPipe(InputStream istrm, OutputStream ostrm) {
        istrm_ = istrm;
        ostrm_ = ostrm;
    }

    public void run() {
        try {
            final byte[] buffer = new byte[1024];
            for (int length = 0; (length = istrm_.read(buffer)) != -1; ) {
                ostrm_.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final OutputStream ostrm_;
    private final InputStream istrm_;
}
Copy after login

The above is the detailed content of How to Properly Execute Multiple Command-Line Commands in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template