可运行jar包调用exe可运行文件,子进程阻塞
背景:
须要在项目的測试工具中加入一个button,点击后直接打开某exe工具。
这个工具的功能是导入txt文件,转为excel报表输出。
无奈解析了两行之后就停止不动了,也不报错。关闭測试工具后,就非常顺畅的继续执行。
原因:
txt转excel报表过程中,中间信息是存在内存中的,缓存区的空间被占满后,程序就被堵塞了,一直在等待缓存区空间资源的释放,所以须要建立线程及时清空缓存区。
解决的方法:
1.创建StreamClean线程类
/*
* 建立线程及时清除堵塞区,避免子线程堵塞(调用外部工具txt->excel时发生的问题。)
*/
public class StreamClean extends Thread {
InputStream is;
String type;
public StreamClean (InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null){
System.out.println(type + ">" + line); //控制台输出
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} 2.在调用exe运行文件处加入下列代码
Process process = null;
try {
process =Runtime.getRuntime().exec(txtToexcel); //txtToexcel是调用工具的dos命令
new StreamClean(process.getInputStream(), "INFO").start();
new StreamClean(process.getErrorStream(), "ERROR").start();
process.waitFor();
}catch (Throwable t) {
t.getStackTrace();
} finally {
if (process != null){
process.destroy();
}
process = null;
}
再运行就木有问题啦~~~

浙公网安备 33010602011771号