背景:
需要在項目的測試工具中添加一個按鈕,點擊後直接打開某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;
}
再執行就木有問題啦~~~