Revision as of 04:57, 23 November 2010 by Han84 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
/**
 * 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);
		}
	}
}


Back to JavaHowTo

Alumni Liaison

Basic linear algebra uncovers and clarifies very important geometry and algebra.

Dr. Paul Garrett