如何使用ant脚本复制属性文件中定义的文件名

时间:2014-02-15 13:12:54

标签: java ant

我有一个属性文件说test.properties.It包含文件名,如下所示。

  • 幅/ WEB-INF / a.java
  • 网/ b.jsp

我想从属性文件test.properties中读取这些文件名,并将这些文件名复制到一个目录中。请帮我解决这个问题.Stack over flow是现在唯一的希望。谢谢提前。

到目前为止,我想解决这个问题的方法是加载属性文件,如下所示

<loadfile property="path" srcFile="${basedir}/test.properties"/>

但是如何解析属性“path”内容?

3 个答案:

答案 0 :(得分:3)

要从文件加载属性,您应该使用loadproperties任务

<强>更新

我修改了答案,添加了第二个示例,该示例从文本文件而不是属性文件中读取。它使用嵌入式groovy脚本来读取文件并将其复制到目标目录。

我警告不要使用ant-contrib。它非常受欢迎,但根据我的经验,如果您需要执行复杂的处理,最好使用普通的编程语言。 Javascript是一个显而易见的选择(不需要额外的jar),但我喜欢groovy,因为它与ANT的完美集成。

示例1:使用属性文件

├── build.properties
├── build.xml
└── src
    ├── a.java
    └── b.jsp

build.properties

file1=src/a.java
file2=src/b.jsp

的build.xml

<project name="demo" default="copy">

  <loadproperties srcFile="build.properties"/>

  <target name="copy">
    <copy file="${file1}" todir="target" verbose="true"/>
    <copy file="${file2}" todir="target" verbose="true"/>
  </target>

</project>

示例2:使用文本文件

├── build.txt
├── build.xml
└── src
    ├── a.java
    └── b.jsp

build.txt

src/a.java
src/b.jsp

的build.xml

<project name="demo" default="copy">

  <target name="bootstrap">
    <mkdir dir="${user.home}/.ant/lib"/>
    <get dest="${user.home}/.ant/lib/groovy-all.jar" src="http://search.maven.org/remotecontent?filepath=org/codehaus/groovy/groovy-all/2.2.1/groovy-all-2.2.1.jar"/>
  </target>

  <target name="copy">
    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
    <groovy>
    new File("build.txt").eachLine {
      ant.copy(file:it, todir:"target", verbose:true)
    }
    </groovy>
  </target>

</project>

备注:

  • 运行“ant bootstrap”从Maven Central安装第三方groovy jar。

答案 1 :(得分:1)

<project name="sample">

  <property file="test.properties"/>

  <target name="copy">
    <copy file="${src1}" todir="dest" />
    <copy file="${src2}" todir="dest" />
  </target>

</project>

这里src1和src2是test.properties中定义的路径变量。

编辑:

在这种情况下,您可以将load文件与for task(逐行读取文件)结合使用,如下所示:

<project name="sample">

  <taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
      <pathelement location="path/to/ant-contrib.jar"/>
    </classpath>
  </taskdef>

<loadfile property="file" srcfile="test.txt"/>

  <target name="copy">
    <for param="line" list="${file}" delimiter="${line.separator}">
      <sequential>
        <copy file="@{line}" todir="dest" />
      </sequential>
    </for>
  </target>
 </project>

您必须使用ant-contrib进行for任务。

希望这有帮助。

答案 2 :(得分:1)

您可能需要将<fileset><files>资源集合与<copy> task一起使用。

<copy todir="${dest.dir}">
    <fileset dir="${src.dir}" includesfile="${list_of_files.file}" />
</copy>

fileset使用相对于dir属性中指定的目录的路径。 如果文件列表文件中的路径是绝对路径,则应使用files而不是fileset

如果要将所有文件复制到单个目录:

src/a.txt   --> dest/a.txt
src/b/b.txt --> dest/b.txt

而不是

src/a.txt   --> dest/a.txt
src/b/b.txt --> dest/b/b.txt

然后使用展平的<copy>任务:

<copy todir="${dest.dir}" flatten="yes">
    ...
</copy>

您可以使用<copy>任务<mapper> element来应用更复杂的名称映射规则。