Defining custom tasks in ANT
25 May 2008Ant provides various core and optional tasks which you use to automate the build process. Very seldom, you need to define your own customized tasks.
To implement a simple custom task, you need to extend the org.apache.tools.ant.Task class and override the execute() method. Follow the sample below:
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; public class FileSorter extends Task { // The method executing the task public void execute() throws BuildException {} }
The execute() method is throws BuildException which will thrown to signal the failure back.
Example follows:
import java.io.*; import java.util.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * A simple example task to sort a file */ public class FileSorter extends Task { private File file, tofile; // The method executing the task public void execute() throws BuildException { System.out.println("Sorting file="+file); try { BufferedReader from = new BufferedReader(new FileReader(file)); BufferedWriter to = new BufferedWriter(new FileWriter(tofile)); List allLines = new ArrayList(); // read in the input file String line = from.readLine(); while (line != null) { allLines.add(line); line = from.readLine(); } from.close(); // sort the list Collections.sort(allLines); // write out the sorted list for (ListIterator i=allLines.listIterator(); i.hasNext(); ) { String s = (String)i.next(); to.write(s); to.newLine(); } to.close(); } catch (FileNotFoundException e) { throw new BuildException(e); } catch (IOException e) { throw new BuildException(e); } } // The setter for the "file" attribute public void setFile(File file) { this.file = file; } // The setter for the "tofile" attribute public void setTofile(File tofile) { this.tofile = tofile; } }
Do try this.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Defining custom tasks in ANT