Java基於Runtime挪用內部法式湧現壅塞的處理辦法。本站提示廣大學習愛好者:(Java基於Runtime挪用內部法式湧現壅塞的處理辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java基於Runtime挪用內部法式湧現壅塞的處理辦法正文
本文實例講述了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法式設計的進修有所贊助。