Java借助Runtime调用外部程序阻塞的代码

王朝学院·作者佚名  2016-05-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

java借助Runtime调用外部程序阻塞的代码有时候在java代码中会调用一些外部程序,比如SwfTools来转换swf、ffmpeg来转换视频等。如果你的代码这样写:Runtime.getRuntime().exec(command),会发现程序一下就执行完毕,而在命令行里要执行一会,是因为java没有等待外部程序的执行完毕,此时就需要使用阻塞,来等待外部程序执行结果:

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是没有问题的。

但我发现对于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;}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航