使用文件列表作为参数编写Ant任务

时间:2016-06-21 08:57:35

标签: java ant task

我想在Java中编写一个Ant任务,它获取一个文件列表作为参数(列表可能有不同的大小)。

我知道您可以扩展Task类并编写setter来设置 参数,但我不知道如何处理整个值列表。

2 个答案:

答案 0 :(得分:1)

您可以使用带有元素的macrodef,而不是编写新的Ant任务。
一些带有1-n文件集的元素的示例,包括来自不同位置的文件:

<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>

sequential元素内的每个嵌套文件集都会执行fs内的任务。

答案 1 :(得分:0)

您可能希望将MatchingTask与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;
    }
}
相关问题