Home >Java >javaTutorial >How Can I Reliably Execute Multiple Command Prompt Commands Using Java?

How Can I Reliably Execute Multiple Command Prompt Commands Using Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 06:01:18533browse

How Can I Reliably Execute Multiple Command Prompt Commands Using Java?

Execute Command Prompt Commands Using Java

Attempting to execute commands from a command prompt through Java using the following code:

String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
OutputStream out = child.getOutputStream();
out.write("cd C:/ /r/n".getBytes());
out.flush();
out.write("dir /r/n".getBytes());
out.close();

may not yield desired results, leaving the command prompt open without executing specified commands.

To address this, consider the following approach:

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);

In addition, define a SyncPipe class to facilitate data transfer:

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_;
}

This method grants the ability to string multiple commands and execute them within a single Windows process. Furthermore, it provides real-time feedback and error handling mechanisms.

The above is the detailed content of How Can I Reliably Execute Multiple Command Prompt Commands Using Java?. For more information, please follow other related articles on the PHP Chinese website!

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