Vincent

Vicent's blog
随笔 - 74, 文章 - 0, 评论 - 5, 引用 - 0
数据加载中……

J2SE5.0新特性之ProcessBuilder

这个例子使用了J2SE5.0的ProcessBuilder类执行外部的程序,相对于 Runtime.exec ,它更方便,可以设置环境变量等。这里使用它在windows下读取物理网卡的地址

  1. package com.kuaff.jdk5package;

  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.ArrayList;
  5. import java.util.List;

  6. public class ProcessBuilderShow
  7. {
  8.     public static List<String> getPhysicalAddress()
  9.     {
  10.         Process p = null;
  11.         //物理网卡列表
  12.         List<String> address = new ArrayList<String>();

  13.         try
  14.         {
  15.             //执行ipconfig /all命令
  16.             p = new ProcessBuilder("ipconfig""/all").start();
  17.          }
  18.         catch (IOException e)
  19.         {
  20.             return  address;
  21.          }
  22.         byte[] b = new byte[1024];
  23.         StringBuffer sb = new StringBuffer();
  24.         //读取进程输出值
  25.         InputStream in = p.getInputStream();
  26.         try
  27.         {
  28.             while (in.read(b)>0)
  29.             {
  30.                 sb.append(new String(b));
  31.              }
  32.          }
  33.         catch (IOException e1)
  34.         {
  35.          }
  36.         finally
  37.         {
  38.             try
  39.             {
  40.                 in.close();
  41.              }
  42.             catch (IOException e2)
  43.             {
  44.              }
  45.          }
  46.         //以下分析输出值,得到物理网卡
  47.         String rtValue = sb.substring(0);
  48.         int i = rtValue.indexOf("Physical Address. . . . . . . . . :");
  49.         while(i>0)
  50.         {
  51.             rtValue = rtValue.substring(i + "Physical Address. . . . . . . . . :".length());
  52.             address.add(rtValue.substring(0,18));
  53.             i = rtValue.indexOf("Physical Address. . . . . . . . . :");
  54.          }
  55.         
  56.         return address;
  57.         
  58.      }
  59.     public static void main(String[] args)
  60.     {
  61.         List<String> address = ProcessBuilderShow.getPhysicalAddress();
  62.         for(String add:address)
  63.         {
  64.             System.out.printf("物理网卡地址:%s%n", add);
  65.          }
  66.      }
  67. }

posted on 2006-08-22 10:45 Binary 阅读(118) 评论(0)  编辑  收藏 所属分类: j2se


只有注册用户登录后才能发表评论。


网站导航: