import java.io.*; import org.apache.tools.ant.taskdefs.*; /** * @author Joshua Daniel Franklin * * example of using the exec subsystem of ant, a full-featured API * over Java's Runtime.exec() including timeout and capturing stdout * and stderr via threads. * * Very handy when calling matlab from java. * * javac -cp ant.jar antExecute.java * java -cp ant.jar:. antExecute * * http://joshuadf.blogspot.com/2007/02/i-needed-something-similar-to-commons.html * */ public class antExecute { public static void main(String[] args) { String mybin = "/bin/sleep"; String pwd = "/tmp/"; String[] cli = {mybin,"4"}; Long timeout = (long) 2000; // seconds * 1000 ExecuteWatchdog execwatch = new ExecuteWatchdog(timeout); ByteArrayOutputStream myOut = new ByteArrayOutputStream(); ByteArrayOutputStream myErr = new ByteArrayOutputStream(); Execute exec = new Execute(new PumpStreamHandler(myOut,myErr),execwatch); exec.setWorkingDirectory(new File(pwd)); exec.setCommandline(cli); try { int exitval = exec.execute(); } catch (Exception e) { e.printStackTrace(); } if (exec.killedProcess()) { System.out.println("watcher killed the process!"); } System.out.println("out: " + myOut.toString()); System.err.println("err: " + myErr.toString()); System.out.println("done"); } }