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/5696740.html