The example in this article describes the solution to the blocking of external programs called by Java based on Runtime, which is a very practical technique. Share it with everyone for your reference. The specific analysis is as follows:
Sometimes some external programs are called in java code, such as SwfTools to convert swf, ffmpeg to convert video, etc. If your code is written like this: Runtime.getRuntime().exec(command), you will find that the program is executed immediately, but it takes a while to execute on the command line because Java does not wait for the execution of the external program to complete. You need to use blocking to wait for the execution results of the external program:
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();
For general external programs, you can use the above blocking code. At least there is no problem with pdf2swf.exe.
But then I discovered that for ffmpeg, the above code would cause the program to get stuck, and another method needed to be used, encapsulating it into a method, as follows:
@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;}I hope that what this article describes will be helpful to everyone's learning of Java programming.