如何获取文件名并将其设置为Ant中的属性?

时间:2012-03-27 09:32:14

标签: java ant

我需要扫描文件夹中的文件并在Ant中将属性设置为文件名,以便稍后使用。 例如,在Jenkins文件夹下有一个test123.tar。我需要使用test * .tar匹配此文件,然后将名为“filename”的属性设置为test123.tar 有可能吗? 非常感谢你!

2 个答案:

答案 0 :(得分:5)

您可以使用pathconvert将文件集转换为文件列表,然后使用loadresourcefilterchain转换为列表中的单个所需值。

<project default="test">

    <target name="test">

        <!-- read your fileset into a property formatted as a list of lines -->
        <pathconvert property="file.list" pathsep="${line.separator}">
            <map from="${basedir}${file.separator}" to=""/>
            <fileset dir="${basedir}">
                <include name="test*.tar"/>
            </fileset>
        </pathconvert>


        <!-- extract a single target file from the list -->
        <loadresource property="file.name">
            <string value="${file.list}"/>
            <filterchain>
                <!-- add your own logic to deal with multiple matches -->
                <headfilter lines="1"/>
            </filterchain>
        </loadresource>

        <!-- print the result -->
        <echo message="file.name: ${file.name}"/>

    </target>

</project>

输出:

$ ls test*.tar
test012.tar  test123.tar  testabc.tar
$
$ ant
Buildfile: C:\tmp\ant\build.xml

test:
     [echo] file.name: test012.tar

BUILD SUCCESSFUL
Total time: 0 seconds

详细输出:

$ ant -v
test:
[pathconvert] Set property file.list = test012.tar
[pathconvert] test123.tar
[pathconvert] testabc.tar
[loadresource] loading test012.tar
[loadresource] test123.tar
[loadresource] testabc.tar into property file.name
[loadresource] loaded 13 characters
     [echo] file.name: test012.tar

BUILD SUCCESSFUL
Total time: 0 seconds

答案 1 :(得分:0)

文件集(搜索)和pathconvert的组合将有所帮助。

<project name="SuperRoot" default="demo" basedir=".">
    <fileset id="afileset" dir="searchfolder" includes="**/test*.jar"/>

    <target name="demo" >
        <pathconvert property="result" refid="afileset" />
        <echo message="found : ${result}"/>
        <basename property="foo.filename" file="${result}"/>
        <echo message="found : ${foo.filename}"/>
        </target>
</project>
相关问题