Java基于Runtime调用外部程序出现阻塞的解决方法
程序员文章站
2024-03-01 13:47:28
本文实例讲述了java基于runtime调用外部程序出现阻塞的解决方法, 是一个很实用的技巧。分享给大家供大家参考。具体分析如下:
有时候在java代码中会调用一些外部程...
本文实例讲述了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 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; }
希望本文所述对大家java程序设计的学习有所帮助。
上一篇: javaweb分页原理详解