如何使用Ant更改文件中的属性值?

时间:2010-03-10 18:25:20

标签: ant properties

示例输入:

SERVER_NAME=server1
PROFILE_NAME=profile1
...

示例输出:

SERVER_NAME=server3
PROFILE_NAME=profile3
...

此文件将在applicationContext.xml中使用。我试过了

<copy file="${web.dir}/jexamples.css_tpl"
         tofile="${web.dir}/jexamples.css" >
    <filterchain>
       <replacetokens>
            <token key="SERVER_NAME" value="server2"/>
            <token key="PROFILE_NAME" value="profi"/>

        </replacetokens>
    </filterchain>
</copy>

但它不起作用。

2 个答案:

答案 0 :(得分:15)

您的filterchain没问题,但您的源文件应如下所示:

SERVER_NAME=@SERVER_NAME@
PROFILE_NAME=@PROFILE_NAME@

此代码(由您提供)

<copy file="${web.dir}/jexamples.css_tpl"
         tofile="${web.dir}/jexamples.css" >
    <filterchain>
       <replacetokens>
            <token key="SERVER_NAME" value="server2"/>
            <token key="PROFILE_NAME" value="profi"/>
        </replacetokens>
    </filterchain>
</copy>

替换令牌并为您提供

SERVER_NAME=server2
PROFILE_NAME=profi

如果您想保留原始文件,一种方法是使用replaceregex

<filterchain>
  <tokenfilter>
    <replaceregex pattern="^[ \t]*SERVER_NAME[ \t]*=.*$"
                  replace="SERVER_NAME=server2"/>
    <replaceregex pattern="^[ \t]*PROFILE_NAME[ \t]*=.*$"
                  replace="PROFILE_NAME=profi"/>
  </tokenfilter>
</filterchain>

这会将SERVER_NAME=的每一行替换为SERVER_NAME=server2PROFILE_NAME=相同)。这将返回获得您描述的输出。

[ \t]*是忽略空格。

答案 1 :(得分:7)

清洁解决方案正在使用“propertyfile”ant任务 - 请参阅http://ant.apache.org/manual/Tasks/propertyfile.html

<copy file="${web.dir}/jexamples.css_tpl"
     tofile="${web.dir}/jexamples.css" />
<propertyfile file="${web.dir}/jexamples.css">
    <entry key="SERVER_NAME" value="server2"/>
</propertyfile>
相关问题