Reputation: 35853
I would like to write an Ant task in Java which gets a list of files as argument (the list may be of varying size).
I know that you can extend the Task
class and write setters to set
parameters, but I do not know how to handle a whole list of values.
Upvotes: 0
Views: 420
Reputation: 10377
Instead of writing a new Ant Task, you may use a macrodef with element.
Some example with an element that takes 1-n filesets, to include files from different locations :
<project>
<macrodef name="listdirs">
<attribute name="file"/>
<element name="fs"/>
<sequential>
<pathconvert property="listcontents" pathsep="${line.separator}">
<fs/>
</pathconvert>
<echo message="${listcontents}" file="@{file}" append="true"/>
</sequential>
</macrodef>
<listdirs file="listdirs.txt">
<fs>
<fileset dir="c:\WKS\_nexus_"/>
<!-- your other filesets .. -->
</fs>
</listdirs>
</project>
The tasks inside sequential
are excuted for every nested fileset inside fs
element.
Upvotes: 1
Reputation: 1333
You may want to use MatchingTask with a DirectoryScanner: http://javadoc.haefelinger.it/org.apache.ant/1.8.1/org/apache/tools/ant/taskdefs/MatchingTask.html
import java.io.File;
import java.text.NumberFormat;
import java.util.Vector;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.taskdefs.MatchingTask;
/**
*
* @author anthony
*/
public class GetSizeTask extends MatchingTask {
private String property;
private String[] files;
protected Vector filesets = new Vector();
/** Creates a new instance of GetSizeTask */
public GetSizeTask() {
}
public void setProperty(String property) {
this.property = property;
}
/**
* Adds a set of files to be deleted.
* @param set the set of files to be deleted
*/
public void addFileset(FileSet set) {
filesets.addElement(set);
}
public void execute() {
if (property == null) {
throw new BuildException("A property must be specified.");
}
if (getProject()==null) {
project = new Project();
project.init();
}
long totalSize = 0l;
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
files = ds.getIncludedFiles();
for (int j=0; j<files.length; j++) {
File file = new File(ds.getBasedir(), files[j]);
totalSize += file.length();
}
}
getProject().setNewProperty(property, NumberFormat.getInstance().format(totalSize));
}
public String[] getFoundFiles() {
return files;
}
}
Upvotes: 0