java執行bat命令碰到的阻塞問題的解決方法
阿新 • • 發佈:2018-12-21
事件起因:在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執行的結果需要自己新增判斷