Runtime.getRuntime().exec(...)使用方法

Runtime.getRuntime().exec(...)使用方法


如果想要了解更多的信息,参阅代码里面给的链接 

下面是这个正确的例子 

  1. public class RuntimeExec {   
  2.     /**  
  3.      * Runtime execute.  
  4.      *  
  5.      * @param cmd the command.  
  6.      * @return success or failure  
  7.      * @see {@link http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4} 
  8.      * @since 1.1  
  9.      */  
  10.     public static boolean runtimeExec(String cmd) {   
  11.         try {   
  12.             Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh""-c", cmd});   
  13.   
  14.             // any error message?   
  15.             StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");   
  16.   
  17.             // any output?   
  18.             StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");   
  19.   
  20.             // kick them off   
  21.             errorGobbler.start();   
  22.             outputGobbler.start();   
  23.   
  24.   
  25.             if (proc.waitFor() != 0) {   
  26.                 System.err.println("执行\"" + cmd + "\"时返回值=" + proc.exitValue());   
  27.                 return false;   
  28.             } else {   
  29.                 return true;   
  30.             }   
  31.         } catch (Exception e) {   
  32.             e.printStackTrace();   
  33.             return false;   
  34.         }   
  35.     }   
  36.   
  37.     static class StreamGobbler extends Thread {   
  38.         InputStream is;   
  39.         String type;   
  40.   
  41.         StreamGobbler(InputStream is, String type) {   
  42.             this.is = is;   
  43.             this.type = type;   
  44.         }   
  45.   
  46.         public void run() {   
  47.             try {   
  48.                 InputStreamReader isr = new InputStreamReader(is);   
  49.                 BufferedReader br = new BufferedReader(isr);   
  50.                 String line = null;   
  51.                 while ((line = br.readLine()) != null)   
  52.                     System.out.println(type + ">" + line);   
  53.             } catch (IOException ioe) {   
  54.                 ioe.printStackTrace();   
  55.             }   
  56.         }   
  57.     }   
  58.   
  59. }  

转载于:https://www.cnblogs.com/duyinqiang/p/5696741.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值