Sometimes external programs are called in Java code, such as Swftools to convert SWF, ffmpeg to convert video, and so on. If your code writes like this: Runtime.getruntime (). EXEC (command), you will find that the program is executed, and at the command line to perform a bit, because Java does not wait for the external program to complete, it is necessary to use blocking, To wait for external program execution results:
InputStream stderr =new InputStreamReader (stderr, "GBK"newnull ; while NULL ) System.out.println (line); int exitvalue = process.waitfor ();
For a general external program to use the above blocking code, at least Pdf2swf.exe is no problem.
But I found that for ffmpeg, the above code will make the program stuck, need to use another way, encapsulated 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 was finishedtry {in = Process.getinputstream (); err = Process.geterrorstream (); Boolean finished = false; Set to True when P was Finishedwhile (!finished) {try {while (in.available () > 0) {//Print the output of our system Callcharacter C = new Character ((char) in.read ()); System.out.print (c);} while (err.available () > 0) {//Print the output of our system callcharacter c = new Character ((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 are set to True.exitvalue = Process.exitvalue (); finished = t Rue;} catch (Illegalthreadstateexception e) {//Process is not finished yet;//Sleep a little to save on CPU Cyclesthread.curren TThread (). Sleep (500);}}} catch (Exception e) {e.printstacktrace ();} finally {try {if (in! = null) {In.close ()}} catch (IOException e) {E.print StackTrace ();} if (err! = null) {try {err.close ();} catch (IOException e) {e.printstacktrace ();}}} return exitvalue;}
Java calling external program blocking code with runtime