Java 如何创建CMD进程并向其发送命令
在Java中,我想创建一个CMD进程并向其发送输入,然后输出进程中显示的信息。是否有任何外部罐子允许我这样做 我尝试过使用Runtime,但在进程关闭之前,一次最多只能运行一个命令Java 如何创建CMD进程并向其发送命令,java,Java,在Java中,我想创建一个CMD进程并向其发送输入,然后输出进程中显示的信息。是否有任何外部罐子允许我这样做 我尝试过使用Runtime,但在进程关闭之前,一次最多只能运行一个命令 Runtime rt=Runtime.getRuntime() 我需要它,以便命令提示符保持打开状态,因为我将运行一个exe文件,该文件根据输入的命令输出不同的信息。您可以在循环中使用ProcessBuilder并继承IO。 这应该将进程的输出写入与调用进程相同的位置。在这种情况下,可能是控制台 有关更多信息,请参阅
Runtime rt=Runtime.getRuntime()代码>
我需要它,以便命令提示符保持打开状态,因为我将运行一个exe文件,该文件根据输入的命令输出不同的信息。您可以在循环中使用ProcessBuilder并继承IO。
这应该将进程的输出写入与调用进程相同的位置。在这种情况下,可能是控制台
有关更多信息,请参阅:
您可以尝试以下方法:
public static void main(String[] args){
List<String> commandArguments = new ArrayList<>();
while(someCondition){
commandArguments.add("cmd.exe");
commandArguments.add("/C");
commandArguments.add(yourCommands); //Read input from console
executeCommand(commandArguments)
}
}
private void executeCommand(List<String> commandArguments){
if(commandArguments != null){
try{
new ProcessBuilder(commandArguments).inheritIO().start().waitFor();
}catch(IOException, InterruptedException ex){
ex.printStacktrace();
}
}
}
publicstaticvoidmain(字符串[]args){
List commandArguments=new ArrayList();
while(某些条件){
commandArguments.add(“cmd.exe”);
commandArguments.add(“/C”);
commandArguments.add(yourCommands);//从控制台读取输入
executeCommand(命令参数)
}
}
私有void executeCommand(列出命令参数){
if(commandArguments!=null){
试一试{
新建ProcessBuilder(commandArguments).Inheritario().start().waitFor();
}捕获(IOException,InterruptedException ex){
例如printStacktrace();
}
}
}
尝试查看JCommander
public static void main(String[] args){
List<String> commandArguments = new ArrayList<>();
while(someCondition){
commandArguments.add("cmd.exe");
commandArguments.add("/C");
commandArguments.add(yourCommands); //Read input from console
executeCommand(commandArguments)
}
}
private void executeCommand(List<String> commandArguments){
if(commandArguments != null){
try{
new ProcessBuilder(commandArguments).inheritIO().start().waitFor();
}catch(IOException, InterruptedException ex){
ex.printStacktrace();
}
}
}