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

use*_*316 11 java for-loop batch-file windows-runtime

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

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

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

我怎样才能做到这一点?

sta*_*tan 24

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

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

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

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

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

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

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

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

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

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

  • 使用ProcessBuilder:`ProcessBuilder builder = new ProcessBuilder("cmd.exe","/ c","command1 && command2"); builder.redirectErrorStream(真); Process process = builder.start(); ... process.getOutputStream()...` (3认同)

Jos*_*ost 14

我会使用Java的ProcessBuilder或其他模拟/使用shell的类.以下片段演示了这个想法(对于Linux使用bash).

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

请注意,它只是一个片段,需要适用于Windows,但一般情况下它应该适用cmd.exe.