本文實例講述了Java基于Runtime調用外部程序出現阻塞的解決方法, 是一個很實用的技巧。分享給大家供大家參考。具體分析如下:
有時候在java代碼中會調用一些外部程序,比如SwfTools來轉換swf、ffmpeg來轉換視頻等。如果你的代碼這樣寫:Runtime.getRuntime().exec(command),會發現程序一下就執行完畢,而在命令行里要執行一會,是因為java沒有等待外部程序的執行完畢,此時就需要使用阻塞,來等待外部程序執行結果:
1
2
3
4
5
6
7
|
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來說,以上代碼會讓程序卡住不動,需要使用另一種方式,封裝成了一個方法,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
@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程序設計的學習有所幫助。