一尘不染

如何通过Java执行cmd命令

java

我正在尝试通过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();

上面的命令打开命令行,但是不执行cddir。有任何想法吗?我正在运行Windows XP,JRE6。

(我已经对问题进行了更详细的修订。以下答案很有用,但不能回答我的问题。)


阅读 1246

收藏
2020-03-04

共2个答案

一尘不染

你发布的代码使用自己的命令启动三个不同的过程。要打开命令提示符然后运行命令,请尝试以下操作(请勿自己尝试):

try {
    // 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();
} catch (IOException e) {
}
2020-03-04
一尘不染

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

SyncPipe类别:

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_;
}
2020-03-04