/** * This method is used for executing the external program. The dealing with streams is critical. * @param command the program file that this method will execute * @return the return value from the "waitFor" method */ public static int exeCommand(String command) { // The initial value of exitVal is not important. int exitVal = 0; try { Process p = Runtime.getRuntime().exec(command); StreamPasser outputGobbler = new StreamPasser(p.getInputStream()); StreamPasser errorGobbler = new StreamPasser(p.getErrorStream()); outputGobbler.start(); errorGobbler.start(); exitVal = p.waitFor(); } catch (InterruptedException ex) { Ts.printErr(ex); } catch (java.io.IOException ex) { Ts.printErr(ex); } return exitVal; } public static void printErr(java.lang.Exception ex) { printErr(ex.getMessage()); }
/** * This class is only for Ts.exeCommand method. */ class StreamPasser extends java.lang.Thread { java.io.InputStream is; StreamPasser(java.io.InputStream is) { this.is = is; } @Override public void run() { try { java.io.InputStreamReader isr = new java.io.InputStreamReader(is); java.io.BufferedReader br = new java.io.BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (java.io.IOException ex) { Ts.printErr(ex); } } }