ProcessBuilder调用外部脚本
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class UsingProcessBuilder {
public static String getCommandResult(List<String> cmds){
String res="";
ProcessBuilder pb = null;
Process p = null;
try{
pb= new ProcessBuilder(cmds);
pb.redirectErrorStream(true);
p = pb.start();
}catch(IOException e){
//记录报错日志--add
return res;
}
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));
//System.out.printf("%s",readbytes);
}
}catch(IOException e1){
}finally {
try{
in.close();
}catch (IOException e2){
}
}
res=sb.toString();
//等待进程退出
try{
int i=p.waitFor();
}catch(InterruptedException e){
}
return res;
};
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> cmds = new ArrayList<String>();
//*****************************************************************
cmds.add("cmd.exe");
cmds.add("/c");
cmds.add("ping www.yahoo.com.cn");//等同于这两个参数分开
String res=UsingProcessBuilder.getCommandResult(cmds);
System.out.printf("%s",res);
}
}