Java基於Runtime調用外部程式出現阻塞的解決方案_java

來源:互聯網
上載者:User

本文執行個體講述了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程式設計的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.