这个例子使用了J2SE5.0的ProcessBuilder类执行外部的程序,相对于Runtime.exec,它更方便,可以设置环境变量等。这里使用它在Windows下读取物理网卡的地址
packagecom.kuaff.JDK5package;
importJava.io.IOException;
importjava.io.InputStream;
importjava.util.ArrayList;
importjava.util.List;
publicclassProcessBuilderShow
{
publicstaticList<String>getPhysicalAddress()
{
Processp=null;
//物理网卡列表
List<String>address=newArrayList<String>();
try
{
//执行ipconfig/all命令
p=newProcessBuilder("ipconfig","/all").start();
}
catch(IOExceptione)
{
returnaddress;
}
byte[]b=newbyte[1024];
StringBuffersb=newStringBuffer();
//读取进程输出值
InputStreamin=p.getInputStream();
try
{
while(in.read(b)>0)
{
sb.append(newString(b));
}
}
catch(IOExceptione1)
{
}
finally
{
try
{
in.close();
}
catch(IOExceptione2)
{
}
}
//以下分析输出值,得到物理网卡
StringrtValue=sb.substring(0);
inti=rtValue.indexOf("PhysicalAddress.........:");
while(i>0)
{
rtValue=rtValue.substring(i "PhysicalAddress.........:".length());
address.add(rtValue.substring(0,18));
i=rtValue.indexOf("PhysicalAddress.........:");
}
returnaddress;
}
publicstaticvoidmain(String[]args)
{
List<String>address=ProcessBuilderShow.getPhysicalAddress();
for(Stringadd:address)
{
System.out.printf("物理网卡地址:%s%n",add);
}
}
}