有的时候我们会需要在Java程序里面执行一个批处理或者其他的外部程序,我们的Java程序需要等待这个外部程序执行结束之后继续执行。
一般会采用如下代码:
Process p=Runtime.getRuntime().exec(batPath);
p.waitFor();
按照API来看,上面的代码时没有问题的。但是经常的,我们会遇到,p.waitFor()在一直等待,也就是说进程一直无法结束,导致程序无法继续执行下去。
所以很多人会采用:
Process p=Runtime.getRuntime().exec(batPath);
Thread.sleep(n*1000);
sleep的缺点显而易见,sleep多久OK呢?
以上问题的产生的本质原因是因为标准输入流被堵塞,我们需要主动把标准输入流中的内容读出来,考虑如下代码,可以很好地解决我们的问题
private boolean isLog = true;
public static void processBat(String batPath){
Process p=Runtime.getRuntime().exec(batPath);
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line=reader.readLine())!=null){
if(isLog){
System.out.println(line);
}
}
}