如何在 Java 的一个 cmd 窗口中运行多个命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18866381/
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-12 11:45:39  来源:igfitidea点击:

How can I run multiple commands in just one cmd windows in Java?

javafor-loopbatch-filewindows-runtime

提问by user2426316

what I would like to do is run a batchfile multiple times from a java application. Therefore I set up a for-loopthat runs this code ntimes:

我想要做的是batch从 Java 应用程序多次运行一个文件。因此,我设置了一个for-loop运行此代码的n时间:

for (int i = 0; i < n; i++) {
    Runtime.getRuntime().exec("cmd /c start somefile.bat");
}

The problem is that now each time the command is run a new cmd window pops up. However, what I want is just onewindow that pops up at the beginning and that is used to display all data from the following command calls.

问题是现在每次运行命令时都会弹出一个新的 cmd 窗口。但是,我想要的只是一个在开始时弹出的窗口,用于显示来自以下命令调用的所有数据。

How can I do that?

我怎样才能做到这一点?

采纳答案by stan

With &&you can execute more than one commands, one after another:

使用&&您可以执行多个命令,一个接一个:

Runtime.getRuntime().exec("cmd /c \"start somefile.bat && start other.bat && cd C:\test && test.exe\"");

Using multiple commands and conditional processing symbols

You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.

For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful. You can use the special characters listed in the following table to pass multiple commands.

& [...] command1 & command2
Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.

&& [...] command1 && command2
Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.

|| [...] command1 || command2
Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).

( ) [...] (command1 & command2)
Use to group or nest multiple commands.

; or , command1 parameter1;parameter2
Use to separate command parameters.

使用多个命令和条件处理符号

您可以使用条件处理符号从单个命令行或脚本运行多个命令。当您使用条件处理符号运行多个命令时,条件处理符号右侧的命令将根据条件处理符号左侧的命令的结果执行操作。

例如,您可能只想在前一个命令失败时运行命令。或者,您可能只想在前一个命令成功时运行命令。您可以使用下表中列出的特殊字符来传递多个命令。

& [...] command1 & command2
用于在一个命令行上分隔多个命令。Cmd.exe 运行第一个命令,然后是第二个命令。

&& [...] command1 && command2
仅当符号前面的命令成功时才用于运行 && 后面的命令。Cmd.exe 运行第一个命令,然后仅当第一个命令成功完成时才运行第二个命令。

|| [...] command1 || command2
用于运行 || 后面的命令 仅当 || 前面的命令 失败。Cmd.exe 运行第一个命令,然后仅当第一个命令未成功完成(收到大于零的错误代码)时才运行第二个命令。

( ) [...] (command1 & command2)
用于分组或嵌套多个命令。

; or , command1 parameter1;parameter2
用于分隔命令参数。

回答by Jost

I would use Java's ProcessBuilderor another class which simulates/uses a shell. The following snippet demonstrates the idea (for Linux with bash).

我会使用 Java 的ProcessBuilder或其他模拟/使用 shell 的类。下面的代码片段演示了这个想法(对于带有 bash 的 Linux)。

import java.util.Scanner;
import java.io.*;

public class MyExec {
    public static void main(String[] args)
    {
        //init shell
        ProcessBuilder builder = new ProcessBuilder( "/bin/bash" );
        Process p=null;
        try {
            p = builder.start();
        }
        catch (IOException e) {
            System.out.println(e);
        }
        //get stdin of shell
        BufferedWriter p_stdin = 
          new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

        // execute the desired command (here: ls) n times
        int n=10;
        for (int i=0; i<n; i++) {
            try {
                //single execution
            p_stdin.write("ls");
            p_stdin.newLine();
            p_stdin.flush();
            }
            catch (IOException e) {
            System.out.println(e);
            }
        }

        // finally close the shell by execution exit command
        try {
            p_stdin.write("exit");
            p_stdin.newLine();
            p_stdin.flush();
        }
        catch (IOException e) {
            System.out.println(e);
        }

    // write stdout of shell (=output of all commands)
    Scanner s = new Scanner( p.getInputStream() );
    while (s.hasNext())
    {
        System.out.println( s.next() );
    }
       s.close();
    }
}

Please note that it is only a snippet, which needs to be adapted for Windows, but in general it should work with cmd.exe.

请注意,它只是一个片段,需要针对 Windows 进行调整,但通常它应该与cmd.exe.