How do I build a list of file names?

六月ゝ 毕业季﹏ 提交于 2019-12-10 16:39:21

问题


I need to write an Ant target that appends together (comma-delimited) a list of '.jar' file names from a folder into a variable, which is later used as input to an outside utility. I am running into barriers of scope and immutability. I have access to ant-contrib, but unfortunately the version I am stuck with does not have access to the 'for' task. Here's what I have so far:

<target name="getPrependJars">
    <var name="prependJars" value="" />
    <foreach param="file" target="appendJarPath">
        <path>
            <fileset dir="${project.name}/hotfixes">
                <include name="*.jar"/>
            </fileset>
        </path>         
    </foreach>

    <echo message="result ${prependJars}" />
</target>


<target name="appendJarPath">
    <if>
        <equals arg1="${prependJars}" arg2="" />
        <then>
            <var name="prependJars" value="-prependJars ${file}" />
        </then>
        <else>
            <var name="prependJars" value="${prependJars},${file}" />
        </else>
    </if>       
</target>

It seems that 'appendJarPath' only modifies 'prependJars' within its own scope. As a test, I tried using 'antcallback' which works for a single target call, but does not help me very much with my list of files.

I realize that I am working somewhat against the grain, and lexical scope is desirable in the vast majority of instances, but i really would like to get this working one way or another. Does anybody have any creative ideas to solve this problem?


回答1:


You might be able to use the pathconvert task, which allows you to specify the separator character as comma.

<target name="getPrependJars">
    <fileset id="appendJars" dir="${project.name}/hotfixes">
        <include name="*.jar" />
    </fileset>
    <pathconvert property="prependJars" refid="appendJars" pathsep="," />

    <echo message="prependJars: ${prependJars}" />
</target>



回答2:


I'd simply write a custom task in Java that (1) takes the folder name, (2) assembles the result string and (3) stores it to the ${prependJars} property.

In ant you just define the task (taskdef) and use like all other tasks afterwards.

I did it once when I was faced with a simliar problem and found that it was very, very easy.

Here's the tutorial.




回答3:


If a system path format is useful to you, you can use the following:

<target name="getPrependJars">
    <path id="prepend.jars.path">
        <fileset dir="${project.name}/hotfixes">
            <include name="*.jar"/>
        </fileset>
    </path>         
    <property name="prependJars" value="${toString:prepend.jars.path}" />

    <echo message="result ${prependJars}" />
</target>


来源:https://stackoverflow.com/questions/2140637/how-do-i-build-a-list-of-file-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!