Java执行cmd命令、bat脚本、linux命令,shell脚本等
1.Windows下执行cmd命令
如复制 D:\tmp\my.txt 到D:\tmp\my_by_only_cmd.txt
现文件如图示:
执行代码:
private static void runWinCmd() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("cmd.exe /c copy D:\\tmp\\my.txt D:\\tmp\\my_by_only_cmd.txt"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); }
结果如图示,执行成功
2.Windows下执行bat脚本
删除多余文件,新建mytest.bat,内容如下
copy D:\tmp\my.txt D:\tmp\my_by_bat.txt
exit
现文件如图示:
执行代码:
private static void runWinBat() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("cmd.exe /c start D:\\tmp\\mytest.bat"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); }
结果如图示,执行成功
3.Linux下执行命令
如复制 /opt/tmp/my.txt 到 /opt/tmp/my_by_copy.txt
现文件如图示:
执行代码:
private static void runLinuxCommand() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("sudo cp /opt/tmp/my.txt /opt/tmp/my_by_copy.txt"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); }
结果如图示,执行成功
4.Linux下执行shell脚本
删除多余文件,新建mytest.sh,内容如下
sudo cp /opt/tmp/my.txt /opt/tmp/my_by_sh.txt
现文件如图示:
执行代码:
private static void runLinuxShell() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("bash /opt/tmp/mytest.sh"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); }
结果如图示,执行成功
Tip:Java的Process对象的waitFor()方法返回值等于0时,说明子进程正常完成退出,如不等于0,则有相应的异常解释,可参考 此处
完整代码如下:
package com.runtime; import java.io.IOException; /** * @author: Convict.Yellow * @date: 2020/10/27 10:28 * @description: TestProcess */ public class TestProcess { public static void main(String[] args) throws IOException, InterruptedException { runWinCmd(); runWinBat(); runLinuxCommand(); runLinuxShell(); } private static void runWinCmd() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("cmd.exe /c copy D:\\tmp\\my.txt D:\\tmp\\my_by_only_cmd.txt"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); } private static void runWinBat() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("cmd.exe /c start D:\\tmp\\mytest.bat"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); } private static void runLinuxCommand() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("sudo cp /opt/tmp/my.txt /opt/tmp/my_by_copy.txt"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); } private static void runLinuxShell() throws IOException, InterruptedException { Process proc = Runtime.getRuntime().exec("bash /opt/tmp/mytest.sh"); int processCode = proc.waitFor(); System.out.println("Process code: " + processCode); } }