ProcessBuilder优点
ProcessBuilder(XXX).start()和Runtime.exec(XXX)功能相同,主要优点在使用过程中感受有:
- 前者是jdk1.5后的新方式
- 配置环境变量时更优雅
- 对当前目录的控制也更合理
- 错误流重定向特别方便
- 进程控制更简洁
ProcessTool.java
package test; import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map; /**
*
* @author King
* @see
* @version createTM:2017年11月23日 下午3:41:38
*/
public class ProcessTool { public static void main(String[] args) throws IOException {
execWindowCmd();
} public static void execWindowCmd() throws IOException { ProcessBuilder pb = new ProcessBuilder();// 命令
Map<String, String> env = pb.environment();// 独立环境变量
System.out.println(env);// 打印环境变量
env.put("MY_NAME", "KING");// 添加环境变量key-value
pb.redirectErrorStream(true);// 重定向错误输出流到正常输出流 try {
pb.directory(new File("d://test1"));// 设置目录test1
pb.command("cmd", "/c", "dir");// 执行命令
Process process1;
process1 = pb.start();// 启动进程
BufferedReader br1;
br1 = new BufferedReader(new InputStreamReader(process1.getInputStream(), "gbk"));
String line1 = null;
while ((line1 = br1.readLine()) != null) {
System.out.println(line1);
} pb.directory(new File("d://test2"));// 设置目录test2
pb.command("cmd", "/c", "dir", ">>", "test1.log");// 执行命令,把结果输出到test1.log
Process process2 = pb.start();// 启动进程
BufferedReader br2 = new BufferedReader(new InputStreamReader(process2.getInputStream(), "gbk"));
String line2 = null;
while ((line2 = br2.readLine()) != null) {//因为结果输出到了文件,所以本处无信息返回
System.out.println(line2);
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
}