事件起因:在Java中可以执行bat文件,有个需求需要执行bat文件才能完成,bat命令中会生成多个文件,在程序运行过程中我惊奇的发现,生成的文件在到一定数量时(当时是10个)就不再增加了,这远远的低于我设定的数量(100个),在我关闭程序后文件的数量又开始增加,我意识到可能是bat运行时被阻塞了,于是在网上查到的解决方案,就是以下这个,亲测可用!
工具类
public class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
public StreamGobbler(InputStream is, String type) {
this(is, type, null);
}
public StreamGobbler(InputStream is, String type, OutputStream redirect) {
this.is = is;
this.type = type;
this.os = redirect;
}
public void run() {
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
if (os != null)
pw = new PrintWriter(os);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);//执行中输出的语句
}
if (pw != null)
pw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (pw != null)
pw.close();
br.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
调用bat
Runtime rt = Runtime.getRuntime();
Process ps = null;
try {
ps = rt.exec("cmd.exe /C start /b " + batDir);//batDir是bat文件路径
//必要的,不然会阻塞
StreamGobbler errorGobbler = new StreamGobbler(ps.getErrorStream(), "ERROR");
errorGobbler.start();
//好像没什么用
StreamGobbler outGobbler = new StreamGobbler(ps.getInputStream(), "STDOUT");
outGobbler.start();
ps.waitFor();
} catch (Exception e1) {
e1.printStackTrace();
}
int success = ps.exitValue();
if (success == 0) {
//启动成功
} else {
//启动失败
}
程序不会等待bat执行完成才接着执行,如果之后有代码要用到bat执行的结果需要自己添加判断