Java executes cmd command or multiple cmd command methods

describe

Sometimes it is necessary to use java code to execute multiple or single cmd commands. Here is how to do it.

accomplish

Runtime.getRuntime().exec("cmd /k start ipconfig");

The above code can be used to execute a single command. If there are multiple commands, it is said on the Internet that the && symbol can be used to connect the commands, but I have tried it, but it does not work on my computer. So if you want to execute multiple commands, write the commands to be executed into a .bat file, and pay attention to the syntax of .bat here. Then execute the bat file with the cmd command.
example:

RuntimeUtil.exec("cmd /c start C:\\Users\\Administrator\\Desktop\\123.bat");

After executing the command, do not close the cmd window, you can refer to the following writing method. (I found it on the Internet), but I tried it, and the execution of ipconfig still closes the window.
cmd.exe /c "command" is to close the command window after executing the cmd command;
cmd.exe /k "command" is to not close the command window after executing the cmd command;
cmd.exe /c start "command" will open a new Execute the cmd command after the window, the original window will be closed;
cmd.exe /k start "command" will open a new window and execute the cmd command, the original window will not be closed;
cmd.exe /k start /b "command" will open a new window The hidden window executes the cmd command, and the original window will not be closed

Guess you like

Origin blog.csdn.net/javaXiaoAnRan/article/details/106312569