如何通过 Java 执行 cmd 命令

2022-09-01 00:52:59

我正在尝试通过Java执行命令行参数。例如:

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

上述操作将打开命令行,但不会执行 或 。有什么想法吗?我正在运行Windows XP,JRE6。cddir

(我修改了我的问题,使其更加具体。以下答案很有帮助,但不要回答我的问题。


答案 1

我在 forums.oracle.com 发现了这个

允许重用一个进程以在 Windows 中执行多个命令:http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

你需要类似的东西

   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");
    // write any other commands you want here
    stdin.close();
    int returnCode = p.waitFor();
    System.out.println("Return code = " + returnCode);

同步管类:

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

答案 2

如果要在cmd shell中运行多个命令,则可以构造如下单个命令:

  rt.exec("cmd /c start cmd.exe /K \"cd c:/ && dir\"");

本页将详细介绍。


推荐