gpt4 book ai didi

java - 在Java程序中执行多行命令

转载 作者:行者123 更新时间:2023-11-30 08:16:06 24 4
gpt4 key购买 nike

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

最佳答案

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

您可以创建一个私有(private)方法,将所有这些命令连接成一个 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);

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

关于java - 在Java程序中执行多行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29645404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com