这里我们主要是调用了 一个方法导致的
process.exitValue()。
Process.exitValue() 采用非阻塞的方式返回,如果没有立即拿到返回值,则抛出异常。
我的解决方法是放在 Process.waitFor(),之前没有注意到这个,必须要放在这个后面。
Process.waitFor() 当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。但是如果我们在调用此方法时,如果不注意的话,很容易出现主线程阻塞,Process也挂起的情况。在调用waitFor() 的时候,Process需要向主线程汇报运行状况,所以要注意清空缓存区,即InputStream和ErrorStream
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
public class Temp implements Runnable {
public void run() {
String PATH_TO_SWF = "D:\\Program Files\\SWFTools\\pdf2swf.exe" ;
String fromFilename = "G:\\test\\read\\suanfa.pdf" ;
String saveFilename = "G:\\test\\read\\xiaoxiaoxxx.swf" ;
List command = new java.util.ArrayList();
command.add(PATH_TO_SWF);
command.add("-o" );
command.add(saveFilename);
command.add("-t" );
command.add(fromFilename);
command.add("-s" );
command.add("languagedir=" + "G:\\test\\read\\xpdf\\chinese-simplified" );
ProcessBuilder builder = new ProcessBuilder();
builder.command(command);
try {
Process convertImgProcess = builder.start();
final InputStream is1 = convertImgProcess.getInputStream();
final InputStream is2 = convertImgProcess.getErrorStream();
new Thread() {
public void run() {
BufferedReader br = new BufferedReader(
new InputStreamReader(is1));
try {
String lineB = null ;
while ((lineB = br.readLine()) != null ) {
if (lineB != null ) System.out.println(lineB);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
BufferedReader br2 = new BufferedReader(
new InputStreamReader(is2));
try {
String lineC = null ;
while ((lineC = br2.readLine()) != null ) {
if (lineC != null ) System.out.println(lineC);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
convertImgProcess.waitFor();
} catch (Exception e) {
System.err.println(e);
}
}
}