在 Java 程序中执行几行命令

Execute several line commands in a Java Programm

我需要在我的 java 程序中执行一些行命令。 例如,我想转到一个目录,然后在其中创建一个文件夹,如下所示:

cd C:\Users\qi11091\Documents\TITAN_Command_Line\FirstTest
mkdir toto

我的问题是我可以执行第一个命令,它可以工作,但我不知道如何在我的程序中执行第二个命令。

这是我的代码

public void TtcnToC(String path){
    System.out.println("Début du programme");
    try{
        System.out.println("Path target verification: "+path);

        String[] mkdir = {"cmd.exe", "/c","cd C:\Users\qi11091\Documents\TITAN_Command_Line\FirstTest", "mkdir titi"};
        String[] mkdir1 = {"cmd.exe", "/c","cd "+ path};
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(mkdir1);

        //Process process1 = runtime.exec(mkdir1);
        //Process process2 = runtime.exec(mkdir2);

        BufferedReader output = getOutput(process);
        BufferedReader error = getError(process);
        String ligne = "";

        while ((ligne = output.readLine()) != null) {
            System.out.println(ligne);
        }

        while ((ligne = error.readLine()) != null) {
            System.out.println(ligne);
        }

        System.out.println("in the shell");
        process.waitFor();
    }

仅作为示例,您可以查看以下代码,

    try { 

        String[] command = new String[2];
        command[0]="cmd /c dir";
        command[1]="cmd /c dir/w";

        Process p;

        for (int i = 0; i < command.length; i++) {
            String cmd = command[i];
            p=Runtime.getRuntime().exec(cmd); 
            p.waitFor();    

            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
            String line=reader.readLine(); 
            while(line!=null) 
            { 
                System.out.println(line); 
                line=reader.readLine(); 
            } 
        }

    } catch(IOException e1) {
        e1.printStackTrace();
    } 
    catch(InterruptedException e2) {
        e2.printStackTrace();
    } 

    System.out.println("Done"); 
}

要连续执行多个命令,您可以使用命令行用于在同一行中执行多个命令的语法在单个命令中执行它们。

您可以创建一个私有方法,将所有这些命令连接成一个 CMD 可以理解的命令:

private String combineCommands(String[] commands){
    String result = "";
    for(String command: commands){
        result = result + command + " && ";
    }
    if(result.length() > 0){
        result = result.subString(0,result.length()-3); // We remove the last && here.
    }
    return result;
}

所以你传递给它一个字符串数组,例如:

String[] myCommands = {"cd C:\Users\qi11091\Documents\TITAN_Command_Line\FirstTest", "mkdir titi"};

然后你可以像以前一样简单地调用你的执行:

String[] mkdir1 = {"cmd.exe", "/c",combineCommands(myCommands)};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(mkdir1);

这样您就不必为要执行的每个命令调用 Runtime