如何通过Java执行cmd命令

joe*_*joe 41 java exec

我试图通过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();
Run Code Online (Sandbox Code Playgroud)

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

(我已将我的问题修改为更具体.以下答案有帮助,但不回答我的问题.)

小智 63

我在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);
Run Code Online (Sandbox Code Playgroud)

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_;
}
Run Code Online (Sandbox Code Playgroud)

  • 很好,链接无效,但这里复制的代码就足够了. (4认同)
  • 这实际上是正确的答案! (2认同)

Vin*_*nie 15

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

  rt.exec("cmd /c start cmd.exe /K \"cd c:/ && dir\"");
Run Code Online (Sandbox Code Playgroud)

这个页面解释了更多.


And*_*yle 5

每次执行都会exec产生一个具有自己环境的新进程。因此,您的第二次调用与第一次调用没有任何联系。它只会更改自己的工作目录,然后退出(即它实际上是一个无操作)。

如果您想撰写请求,则需要在一次调用中完成此操作exec。Bash 允许在一行中指定多个命令(如果命令之间用分号分隔);Windows CMD 可能允许相同的操作,如果不允许,总是有批处理脚本。

正如 Piotr 所说,如果这个示例确实是您想要实现的目标,那么您可以使用以下命令更高效、有效且平台安全地执行相同的操作:

String[] filenames = new java.io.File("C:/").list();
Run Code Online (Sandbox Code Playgroud)


Pet*_*ego 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) {
}
Run Code Online (Sandbox Code Playgroud)

  • 哎呀,我喜欢带有免责声明的代码片段:“我自己从未尝试过。” >_< (69认同)
  • 为什么它被批准了..它是误报! (14认同)
  • 谢谢。这将打开命令行,但不会执行 cd 或 dir 命令。 (4认同)
  • 这打开了命令行,但它不执行 cd 或 dir 命令,为什么? (4认同)
  • 下面的答案有实际答案。 (4认同)