Java基于Runtime調(diào)用外部程序出現(xiàn)阻塞的解決方法
本文實(shí)例講述了Java基于Runtime調(diào)用外部程序出現(xiàn)阻塞的解決方法, 是一個(gè)很實(shí)用的技巧。分享給大家供大家參考。具體分析如下:
有時(shí)候在java代碼中會(huì)調(diào)用一些外部程序,比如SwfTools來(lái)轉(zhuǎn)換swf、ffmpeg來(lái)轉(zhuǎn)換視頻等。如果你的代碼這樣寫(xiě):Runtime.getRuntime().exec(command),會(huì)發(fā)現(xiàn)程序一下就執(zhí)行完畢,而在命令行里要執(zhí)行一會(huì),是因?yàn)閖ava沒(méi)有等待外部程序的執(zhí)行完畢,此時(shí)就需要使用阻塞,來(lái)等待外部程序執(zhí)行結(jié)果:
InputStream stderr = process.getInputStream(); InputStreamReader isr = new InputStreamReader(stderr, "GBK"); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) System.out.println(line); int exitValue = process.waitFor();
對(duì)于一般的外部程序使用上面的阻塞代碼就可以,至少pdf2swf.exe是沒(méi)有問(wèn)題的。
但是緊接著又發(fā)現(xiàn)對(duì)于ffmpeg來(lái)說(shuō),以上代碼會(huì)讓程序卡住不動(dòng),需要使用另一種方式,封裝成了一個(gè)方法,如下:
@SuppressWarnings("static-access") public static int doWaitFor(Process process) { InputStream in = null; InputStream err = null; int exitValue = -1; // returned to caller when p is finished try { in = process.getInputStream(); err = process.getErrorStream(); boolean finished = false; // Set to true when p is finished while (!finished) { try { while (in.available() > 0) { // Print the output of our system call Character c = new Character((char) in.read()); System.out.print(c); } while (err.available() > 0) { // Print the output of our system call Character c = new Character((char) err.read()); System.out.print(c); } // Ask the process for its exitValue. If the process // is not finished, an IllegalThreadStateException // is thrown. If it is finished, we fall through and // the variable finished is set to true. exitValue = process.exitValue(); finished = true; } catch (IllegalThreadStateException e) { // Process is not finished yet; // Sleep a little to save on CPU cycles Thread.currentThread().sleep(500); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } if (err != null) { try { err.close(); } catch (IOException e) { e.printStackTrace(); } } } return exitValue; }
希望本文所述對(duì)大家Java程序設(shè)計(jì)的學(xué)習(xí)有所幫助。
相關(guān)文章
在jmeter的beanshell中用java獲取系統(tǒng)當(dāng)前時(shí)間的簡(jiǎn)單實(shí)例
這篇文章介紹了在jmeter的beanshell中用java獲取系統(tǒng)當(dāng)前時(shí)間的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-09-09基于Java實(shí)現(xiàn)XML文件的解析與更新
配置文件可以有很多種格式,包括?INI、JSON、YAML?和?XML。每一種編程語(yǔ)言解析這些格式的方式都不同。本文將通過(guò)Java語(yǔ)言實(shí)現(xiàn)XML文件的解析與更新,需要的可以參考一下2022-03-03Java調(diào)用CXF WebService接口的兩種方式實(shí)例
今天小編就為大家分享一篇關(guān)于Java調(diào)用CXF WebService接口的兩種方式實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03Java數(shù)據(jù)結(jié)構(gòu)之鏈表相關(guān)知識(shí)總結(jié)
今天給大家?guī)?lái)關(guān)于Java數(shù)據(jù)結(jié)構(gòu)的相關(guān)知識(shí),文章圍繞Java鏈表展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06