View RSS Feed

My Java Tips

Defining custom tasks in ANT

Rate this Entry
by , 11-06-2011 at 05:49 PM (610 Views)
Ant 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:

Java Code:
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:


Java Code:
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.

Submit "Defining custom tasks in ANT" to Facebook Submit "Defining custom tasks in ANT" to Digg Submit "Defining custom tasks in ANT" to del.icio.us Submit "Defining custom tasks in ANT" to StumbleUpon Submit "Defining custom tasks in ANT" to Google

Tags: None Add / Edit Tags
Categories
Ant

Comments