机器人论坛
直播中

刘溪

7年用户 192经验值
私信 关注
[问答]

请问Java如何执行cmd命令、bat脚本、linux命令,shell脚本?

Java如何执行cmd命令、bat脚本、linux命令,shell脚本

回帖(4)

林邵嫔

2020-11-10 15:36:37
Windows下执行cmd命令
如复制 D:tmpmy.txt 到D:tmpmy_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);    }
结果如图示,执行成功
举报

陈龙

2020-11-10 15:36:48
Windows下执行bat脚本
删除多余文件,新建mytest.bat,内容如下
copy D:tmpmy.txt D:tmpmy_by_bat.txtexit
现文件如图示:


执行代码:
    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);    }
结果如图示,执行成功

举报

黄明光

2020-11-10 15:37:00
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);    }
结果如图示,执行成功
举报

谭齐慧

2020-11-10 15:37:12
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);    }
结果如图示,执行成功

举报

更多回帖

发帖
×
20
完善资料,
赚取积分