ProcessBuilder执行本地命令
/**关键技术剖析
* 用本命令名和命令的参数选项构造ProcessBuilder对象,它的start方法执行命令,启动一个进程,返回一个Process对象
* ProcessBuilder的environment方法获得运行进程的环境变量,得到一个Map,可以修改环境变量
* ProcessBuilder的directory方法切换工作目录
* Process的getInputStream方法获得进程的标准输出流,getErrorStream方法获得进程的错误输出流
*/
实现的demo:
/**
* 在J2SE5.0之前使用Runtime的exec方法执行本地命令.
* 在J2Se5.0之后,可以使用ProcessBuilder执行本地命令
* 它提供的功能更加丰富,能够设置设置工作目录、环境变量等
* 本例PorcessBuilder执行Windows操作系统的"ipconfig/all"命令,获取本机网卡的MAC地址
*/
public class UsingProcessBuilder {
/**获取Windows系统下的网卡的MAC地址*/
public static List<String> getPhysicalAddress(){
Process p = null;
List<String> address = new ArrayList<String>(); //物理网卡列表
try{
p = new ProcessBuilder("ipconfig","/all").start(); //执行ipconfig/all命令
}catch(IOException e){
return address;
}
byte[] b = new byte[1024];
int readbytes = -1;
StringBuffer sb = new StringBuffer();
//读取进程输出值
//在JAVA IO中,输入输出是针对JVM而言,读写是针对外部数据源而言
InputStream in = p.getInputStream();
try{
while((readbytes = in.read(b)) != -1){
sb.append(new String(b,0,readbytes));
}
}catch(IOException e1){
}finally {
try{
in.close();
}catch (IOException e2){
}
}
//以下是分析输出值,得到物理网卡
String rtValue = sb.toString();
int i = rtValue.indexOf("Physical Address. . . . . . . . . :");
while (i > 0){
rtValue = rtValue.substring(i + "Physical Address. . . . . . . . . :".length());
address.add(rtValue.substring(1,18));
i = rtValue.indexOf("Physical Address. . . . . . . . . :");
}
return address;
}
public static void main(String[] args){
List<String> address = UsingProcessBuilder.getPhysicalAddress();
for(String add : address){
System.out.printf("物理网卡地址: %s%n",add);
}
}
}
代码中有点瑕疵,但是基本实现啊就是这样。