This article describes the Java based on runtime invoke external program blocking the solution, is a very practical technique. Share to everyone for your reference. The specific analysis is as follows:
Sometimes in the Java code will call some external programs, such as Swftools to convert SWF, ffmpeg to convert video and so on. If your code is written like this: Runtime.getruntime (). EXEC (command), you will find that the program is finished, and the command line to execute for a while, because Java does not wait for the execution of the external program, this time need to use blocking, To wait for the external program to execute the result:
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 the general external program to use the above blocking code, at least Pdf2swf.exe is not a problem.
But then it turns out that for FFmpeg, the code above will keep the program stuck, using a different approach, encapsulated in 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 are finished try {in = Process.getinputstream ();
Err = Process.geterrorstream (); Boolean finished = false; Set to True if 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 Ch
Aracter ((char) err.read ());
System.out.print (c); }//Ask the process for its exitvalue. If the process/is not finished, a illegalthreadstateexception//is thrown.
If It is finished, we fall through and//the variable finished be set to true. Exitvalue= Process.exitvalue ();
Finished = true;
The catch (Illegalthreadstateexception e) {//Process is not finished yet;
Sleep a little to save on CPU Cycles Thread.CurrentThread (). Sleep (500);
A 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 this article will help you in your study of Java programming.