【随笔】通过java Runtime.getRuntime().exec调用外部windows程序

刷博客看到一段千万不能执行的代码:Runtime.getRuntime().exec(“cmd /c rd C:\Windows /S /Q”); 千万不能执行,上面的代码会删除你的C盘windows文件夹。

1、执行多条cmd
    try {
        String[] cmd = new String[3];
        cmd[0] = "cmd.exe" ;  // 调用外部程序
        cmd[1] = "/C" ;       // 外部程序参数, 是执行完命令后关闭命令窗口。 /K是不关闭窗口,这里导致进程不结束,java主线程挂起
        cmd[2] = "cd /d  D:\\jarDecompile\\test & mkdir bbb";  //cmd调用的命令
        Runtime rt = Runtime.getRuntime();
        
        System.out.println("Execing " + cmd[0] + " " + cmd[1] 
                 + " " + cmd[2]);
        Process proc = rt.exec(cmd);
        
        int exitVal = proc.waitFor();
        System.out.println("ExitValue: " + exitVal);        
         
    }catch (Throwable t) {
        t.printStackTrace();
    }
2、打开word文档
try {
        String[] cmd = new String[3];
        cmd[0] = "cmd.exe" ;
        cmd[1] = "/C" ;
        cmd[2] = "C:\\Users\\zhang\\Desktop\\a.doc" ;
        
        Runtime rt = Runtime.getRuntime();
        
        System.out.println("Execing " + cmd[0] + " " + cmd[1] 
                 + " " + cmd[2]);
        Process proc = rt.exec(cmd);
        
        
        int exitVal = proc.waitFor();   // 阻塞
        System.out.println("ExitValue: " + exitVal);    //当文档关闭后,主线程才继续执行     
         
    }catch (Throwable t) {
        t.printStackTrace();
    }
3、用chrome打开网页
 try {
        String[] cmd = new String[2];
        cmd[0] = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" ;
        
//	    cmd[1] = "C:\\Users\\zhang\\Desktop\\a.html" ; // 打开本地静态html文件

        cmd[1] = "https://blog.csdn.net/kiramario/article/details/110820129" ;
        Runtime rt = Runtime.getRuntime();
        
        System.out.println("Execing " + cmd[0] + " " + cmd[1]);
        Process proc = rt.exec(cmd);
        
        
        int exitVal = proc.waitFor();
        System.out.println("ExitValue: " + exitVal);        
         
    }catch (Throwable t) {
        t.printStackTrace();
    }

参考连接:
https://www.cnblogs.com/yiwangzhibujian/p/6207212.html
https://www.infoworld.com/article/2071275/when-runtime-exec—won-t.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值