调用系统其他进程,未等被启动进程进行完,java主进程就继续往下执行了,本以为调用procc.waitfor()可以解决问题,未果,google之发现如下方法:
代码:
//对process.waitFor()的改造,被启动的进程会因为缓冲区不够而被阻塞无法启动,调用该方法可以成功 public static int doWaitFor(Process p) { int exitValue = -1; // returned to caller when p is finished try { InputStream in = p.getInputStream(); InputStream err = p.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 = p.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) { // unexpected exception! print it out for debugging... System.err.println( "doWaitFor(): unexpected exception - " + e.getMessage()); } // return completion status to caller return exitValue; }