在Java程序中执行多个行命令

时间:2015-04-15 08:35:00

标签: java cmd runtime

我需要在我的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();
    }

2 个答案:

答案 0 :(得分:1)

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

您可以创建一个私有方法,将所有这些命令连接到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数组,例如:

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

答案 1 :(得分:0)

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

    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"); 
}
相关问题