Java calls an external program blocking solution based on Runtime
- 2020-04-01 03:27:41
- OfStack
This article illustrates an example of how Java can block calls to external programs based on Runtime. Share with you for your reference. Specific analysis is as follows:
Sometimes external programs are called in Java code, such as SwfTools to convert SWF, ffmpeg to convert video, and so on. If your code reads: Runtime. GetRuntime (). Exec (command), you will find that the program will execute in one go, and in the command line will execute for a while.
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 using the above blocking code can be, at least pdf2swf.exe is no problem.
But then I found out that for ffmpeg, the above code would make the program stuck, so I needed to use another way to encapsulate 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 this article will be helpful to your Java programming study.