如何通过Java执行cmd命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4157303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:09:32  来源:igfitidea点击:

How to execute cmd commands via Java

javaexec

提问by joe

I am trying to execute command line arguments via Java. For example:

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

The above opens the command line but does not execute cdor dir. Any ideas? I am running Windows XP, JRE6.

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

(I have revised my question to be more specific. The following answers were helpful but do not answer my question.)

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

采纳答案by Peter Knego

The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):

您发布的代码启动了三个不同的进程,每个进程都有自己的命令。要打开命令提示符然后运行命令,请尝试以下操作(我自己从未尝试过):

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) {
}

回答by Piotr

Try this link

试试这个链接

You do not use "cd" to change the directory from which to run your commands. You need the full path of the executable you want to run.

您不使用“cd”来更改运行命令的目录。您需要要运行的可执行文件的完整路径。

Also, listing the contents of a directory is easier to do with the File/Directory classes

此外,使用 File/Directory 类更容易列出目录的内容

回答by Carles Barrobés

Each of your exec calls creates a process. You second and third calls do not run in the same shell process you create in the first one. Try putting all commands in a bat script and running it in one call: rt.exec("cmd myfile.bat");or similar

您的每个 exec 调用都会创建一个进程。您的第二个和第三个调用不在您在第一个调用中创建的同一个 shell 进程中运行。尝试将所有命令放在一个 bat 脚本中并在一次调用中运行它: rt.exec("cmd myfile.bat");或类似的

回答by Andrzej Doyle

Every execution of execspawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its ownworking directory and then exit (i.e. it's effectively a no-op).

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

If you want to compose requests, you'll need to do this within a single call to exec. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.

如果要编写请求,则需要在对exec. 如果用分号分隔,Bash 允许在一行中指定多个命令;Windows CMD 可能允许相同,如果没有,总是有批处理脚本。

As Piotr says, if this example is actuallywhat you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:

正如 Piotr 所说,如果这个示例实际上是您想要实现的目标,那么您可以通过以下方式更高效、有效和平台安全地执行相同的操作:

String[] filenames = new java.io.File("C:/").list();

回答by Vincent Ramdhanie

If you want to run several commands in the cmd shell then you can construct a single command like this:

如果你想在 cmd shell 中运行多个命令,那么你可以构造一个这样的命令:

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

This pageexplains more.

这个页面解释了更多。

回答by Hyman

This because every runtime.exec(..)returns a Processclass that should be used after the execution instead that invoking other commands by the Runtimeclass

这是因为每个都runtime.exec(..)返回一个Process应该在执行后使用的类,而不是调用Runtime该类的其他命令

If you look at Process docyou will see that you can use

如果您查看Process doc,您将看到您可以使用

  • getInputStream()
  • getOutputStream()
  • getInputStream()
  • getOutputStream()

on which you should work by sending the successive commands and retrieving the output..

您应该通过发送连续命令并检索输出来处理它。

回答by Kelly S. French

Writing to the out stream from the process is the wrong direction. 'out' in that case means from the process to you. Try getting/writing to the input stream for the process and reading from the output stream to see the results.

从进程写入输出流是错误的方向。在这种情况下,“out”意味着从流程到您。尝试获取/写入进程的输入流并从输出流读取以查看结果。

回答by Pepe

I found this in forums.oracle.com

我在forums.oracle.com 上找到了这个

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

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

You need something like

你需要类似的东西

   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:

同步管道类:

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

回答by singe3

As i also faced the same problem and because some people here commented that the solution wasn't working for them, here's the link to the post where a working solution has been found.

由于我也遇到了同样的问题,并且因为这里的一些人评论说该解决方案对他们不起作用,这里是找到有效解决方案的帖子的链接。

https://stackoverflow.com/a/24406721/3751590

https://stackoverflow.com/a/24406721/3751590

Also see the "Update" in the best answer for using Cygwin terminal

另请参阅使用 Cygwin 终端的最佳答案中的“更新”