如果 exec() 方法没有立即抛出异常,则仅意味着它可以执行外部进程。然而,这并不意味着它成功执行或它甚至正确执行。
有很多方法可以检查外部进程是否成功执行,下面列出了少数几种方法:
使用 Process.getErrorStream() 和 Process.getInputStream() 方法从外部进程读取输出。
查看外部进程的退出代码,代码0代表正常执行,否则可能发生错误。
考虑添加以下代码以进行调试:
public void addImg(){
try{
Runtime r = Runtime.getRuntime();
//Don't use this one...
//Process p = r.exec("/usr/bin/python2.7 ../wc.py");
//p.waitFor();
//p.destroy();
//Use absolute paths (e.g blahblah/foo/bar/wc.py)
p = r.exec("python2.7 ../wc.py");
//Set up two threads to read on the output of the external process.
Thread stdout = new Thread(new StreamReader(p.getInputStream()));
Thread stderr = new Thread(new StreamReader(p.getErrorStream()));
stdout.start();
stderr.start();
int exitval = p.waitFor();
p.destroy();
//Prints exit code to screen.
System.out.println("Process ended with exit code:" + exitval);
}catch(Exception e){
String cause = e.getMessage();
System.out.print(cause);
}
}
private class StreamReader implements Runnable{
private InputStream stream;
private boolean run;
public StreamReader(Inputstream i){
stream = i;
run = true;
}
public void run(){
BufferedReader reader;
try{
reader = new BufferedReader(new InputStreamReader(stream));
String line;
while(run && line != null){
System.out.println(line);
}
}catch(IOException ex){
//Handle if you want...
}finally{
try{
reader.close();
}catch(Exception e){}
}
}
}
此外,尝试在调用外部应用程序时使用 ProcessBuilder,尽管需要更多代码,但我发现它更容易使用。