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

Xia*_*Yao 3 java ant

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

sud*_*ode 6

你可以使用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>
Run Code Online (Sandbox Code Playgroud)

输出:

$ 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
Run Code Online (Sandbox Code Playgroud)

详细输出:

$ 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
Run Code Online (Sandbox Code Playgroud)