JDK5.0特性,使用ProcessBuilder执行本地命令

  1 import java.io.BufferedReader;
  2 
  3 import java.io.BufferedWriter;
  4 
  5 import java.io.File;
  6 
  7 import java.io.IOException;
  8 
  9 import java.io.InputStream;
 10 
 11 import java.io.InputStreamReader;
 12 
 13 import java.io.OutputStreamWriter;
 14 
 15 import java.util.ArrayList;
 16 
 17 import java.util.Arrays;
 18 
 19 import java.util.Iterator;
 20 
 21 import java.util.List;
 22 
 23 import java.util.Map;
 24 
 25  
 26 
 27 /**
 28 
 29  * 在J2SE5.0之前使用Runtime的exec方法执行本地命令.
 30 
 31  * 在J2Se5.0之后,可以使用ProcessBuilder执行本地命令
 32 
 33  * 它提供的功能更加丰富,能够设置设置工作目录、环境变量等
 34 
 35  * 本例PorcessBuilder执行Windows操作系统的"ipconfig/all"命令,获取本机网卡的MAC地址
 36 
 37 */
 38 
 39 /**关键技术剖析
 40 
 41  * 用本命令名和命令的参数选项构造ProcessBuilder对象,它的start方法执行命令,启动一个进程,返回一个Process对象
 42 
 43  * ProcessBuilder的environment方法获得运行进程的环境变量,得到一个Map,可以修改环境变量
 44 
 45  * ProcessBuilder的directory方法切换工作目录
 46 
 47  * Process的getInputStream方法获得进程的标准输出流,getErrorStream方法获得进程的错误输出流
 48 
 49 */
 50 
 51 public class UsingProcessBuilder {
 52 
 53        /**获取Windows系统下的网卡的MAC地址*/
 54 
 55        public static List<String> getPhysicalAddress(){
 56 
 57               Process p = null;
 58 
 59               List<String> address = new ArrayList<String>(); //物理网卡列表
 60 
 61               try{
 62 
 63                      p = new ProcessBuilder("ipconfig","/all").start(); //执行ipconfig/all命令
 64 
 65               }catch(IOException e){
 66 
 67                      return address;
 68 
 69               }
 70 
 71               byte[] b = new byte[1024];
 72 
 73               int readbytes = -1;
 74 
 75               StringBuffer sb = new StringBuffer();
 76 
 77               //读取进程输出值
 78 
 79               //在JAVA IO中,输入输出是针对JVM而言,读写是针对外部数据源而言
 80 
 81               InputStream in = p.getInputStream();
 82 
 83               try{
 84 
 85                      while((readbytes = in.read(b)) != -1){
 86 
 87                             sb.append(new String(b,0,readbytes));
 88 
 89                      }
 90 
 91               }catch(IOException e1){
 92 
 93               }finally {
 94 
 95                      try{
 96 
 97                             in.close();
 98 
 99                      }catch (IOException e2){
100 
101                      }
102 
103               }
104 
105               //以下是分析输出值,得到物理网卡
106 
107               String rtValue = sb.toString();
108 
109               int i = rtValue.indexOf("Physical Address. . . . . . . . . :");
110 
111               while (i > 0){
112 
113                      rtValue = rtValue.substring(i + "Physical Address. . . . . . . . . :".length());
114 
115                      address.add(rtValue.substring(1,18));
116 
117                      i = rtValue.indexOf("Physical Address. . . . . . . . . :");
118 
119               }
120 
121               return address;
122 
123        }
124 
125        /**执行自定义的一个命令,该命令放在C:/temp下,并且需要两个环境变量的支持*/
126 
127        public static boolean executeMyCommand1(){
128 
129               //创建系统进程创建器
130 
131               ProcessBuilder pb = new ProcessBuilder("myCommand","myArg1","myArg2");
132 
133               Map<String, String> env = pb.environment(); //获得进程的环境
134 
135               //设置和去除环境变量
136 
137               env.put("VAR1", "myValue");
138 
139               env.remove("VAR0");
140 
141               env.put("VAR2", env.get("VAR1") + ";");
142 
143               //迭代环境变量,获取属性名和属性值
144 
145               Iterator it=env.keySet().iterator();
146 
147               String sysatt = null;
148 
149               while(it.hasNext())
150 
151               {
152 
153                      sysatt = (String)it.next();
154 
155                      System.out.println("System Attribute:"+sysatt+"="+env.get(sysatt));
156 
157               }
158 
159               pb.directory(new File("C:/temp"));
160 
161               try{
162 
163                      Process p = pb.start(); //得到进程实例
164 
165                      //等待进程执行完毕
166 
167                      if(p.waitFor() != 0){
168 
169                             //如果进程运行结果不为0,表示进程是错误退出的
170 
171                             //获得进程实例的错误输出
172 
173                             InputStream error = p.getErrorStream();
174 
175                             //do something
176 
177                      }
178 
179                      InputStream sdin = p.getInputStream(); //获得进程实例的标准输出
180 
181                      //do something
182 
183               }catch(IOException e){
184 
185               }catch(InterruptedException e){
186 
187               }
188 
189               return true;
190 
191        }
192 
193        public static void executeMyCommand2(){
194 
195               ProcessBuilder pb = null;
196 
197               String sysatt = null;
198 
199               try
200 
201         {
202 
203             //创建一个进程示例
204 
205             pb = new ProcessBuilder("cmd.exe");
206 
207             //获取系统参数并打印显示
208 
209             Map<String, String> env = pb.environment();
210 
211             Iterator it=env.keySet().iterator();
212 
213             while(it.hasNext())
214 
215             {
216 
217                  sysatt = (String)it.next();
218 
219                 System.out.println("System Attribute:"+sysatt+"="+env.get(sysatt));
220 
221             }
222 
223             //设置工作目录
224 
225             pb.directory(new File("d://myDir"));
226 
227             Process p = pb.start();
228 
229             //将要执行的Windows命令写入
230 
231             BufferedWriter bw=new BufferedWriter(newOutputStreamWriter(p.getOutputStream()));
232 
233             //'/r/n'是必须写入的     
234 
235             bw.write("test.bat /r/n");
236 
237             bw.write("ping -t www.yahoo.com.cn /r/n");
238 
239             //flush()方法是必须调用的
240 
241             bw.flush();
242 
243             //将执行结果打印显示
244 
245             InputStream is = p.getInputStream();
246 
247             InputStreamReader isr = new InputStreamReader(is, "GBK");
248 
249             BufferedReader br = new BufferedReader(isr);
250 
251             String line;
252 
253             while ((line = br.readLine()) != null)
254 
255             {
256 
257                 System.out.println(line);
258 
259             }
260 
261         }
262 
263         catch (Exception e)
264 
265         {
266 
267             e.printStackTrace();
268 
269         }
270 
271        }
272 
273        public static void main(String[] args){
274 
275               List<String> address = UsingProcessBuilder.getPhysicalAddress();
276 
277               for(String add : address){
278 
279                      System.out.printf("物理网卡地址: %s%n",add);
280 
281               }
282 
283               executeMyCommand1();
284 
285               executeMyCommand2();
286 
287        }
288 
289 }

来自:http://www.cnblogs.com/taven/archive/2011/12/17/2291460.html

原文地址:https://www.cnblogs.com/sunxucool/p/3842412.html