国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Java借助Runtime調(diào)用外部程序阻塞的代碼

2019-11-14 21:10:31
字體:
供稿:網(wǎng)友
java借助Runtime調(diào)用外部程序阻塞的代碼

有時候在java代碼中會調(diào)用一些外部程序,比如SwfTools來轉(zhuǎn)換swf、ffmpeg來轉(zhuǎn)換視頻等。如果你的代碼這樣寫:Runtime.getRuntime().exec(command),會發(fā)現(xiàn)程序一下就執(zhí)行完畢,而在命令行里要執(zhí)行一會,是因為java沒有等待外部程序的執(zhí)行完畢,此時就需要使用阻塞,來等待外部程序執(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();

對于一般的外部程序使用上面的阻塞代碼就可以,至少pdf2swf.exe是沒有問題的。

但我發(fā)現(xiàn)對于ffmpeg來說,以上代碼會讓程序卡住不動,需要使用另一種方式,封裝成了一個方法,如下:

     @SuppressWarnings("static-access")public static int doWaitFor(Process process) {InputStream in = null;InputStream err = null;int exitValue = -1; // returned to caller when p is finishedtry {in = process.getInputStream();err = process.getErrorStream();boolean finished = false; // Set to true when p is finishedwhile (!finished) {try {while (in.available() > 0) {// Print the output of our system callCharacter c = new Character((char) in.read());System.out.print(c);}while (err.available() > 0) {// Print the output of our system callCharacter 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 cyclesThread.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;}

  


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 招远市| 即墨市| 兴国县| 无极县| 长垣县| 曲麻莱县| 南丰县| 安溪县| 高碑店市| 得荣县| 利津县| 霍邱县| 青河县| 军事| 海门市| 如东县| 六盘水市| 汤原县| 葫芦岛市| 灵丘县| 武威市| 彭州市| 政和县| 绥芬河市| 措勤县| 铜陵市| 广东省| 辛集市| 舟山市| 普陀区| 贺兰县| 贵定县| 文昌市| 光山县| 资兴市| 万载县| 巴里| 宜君县| 镇巴县| 法库县| 虹口区|