2013-05-28 114 views
1

我有一個包含鍵和值,如下所示的屬性文件:通過一個屬性遍歷文件

TC_name1=true 
Tc_name2=false 

我需要一個Ant腳本通過這個屬性文件進行迭代,並與值等於真只得到鑰匙。

另外我想知道是否有可能使用.ini文件作爲我們的屬性文件。

請幫我解決這個問題,因爲我搜索了一下,但無法找到解決方案。

+0

,你可以在這裏找到答案http://stackoverflow.com/questions/ 3056395/how-can-i-iterate-over-properties-from-a-file – dipu

回答

4

的build.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<project default="load"> 
    <target name="load"> 

     <!-- load the properties as plain text into a property --> 
     <loadfile property="trueProps" srcfile="load.properties"> 
      <!-- only load affirmative values of properties --> 
      <filterchain> 
       <linecontainsregexp> 
        <regexp pattern="=\s*(true|yes|on)\s*$" /> 
       </linecontainsregexp> 
      </filterchain> 
      <!-- prefix for easy retrieval --> 
      <filterchain> 
       <prefixlines prefix="testing." /> 
      </filterchain> 
     </loadfile> 

     <!-- print the property contents --> 
     <echo taskname="trueProps">${trueProps}</echo> 

     <!-- extract the keys --> 
     <loadresource property="trueKeys" > 
      <string>${trueProps}</string> 
      <filterchain> 
       <replaceregex pattern="=\s*(true|yes|on)\s*$" replace="" /> 
      </filterchain> 
     </loadresource> 

     <!-- print the keys --> 
     <echo taskname="trueKeys">${trueKeys}</echo> 

     <!-- load the contents of the variable as ant properties --> 
     <loadproperties> 
      <string>${trueProps}</string> 
     </loadproperties> 

     <!-- confirm the properties are loaded as expected --> 
     <echoproperties prefix="testing." /> 
    </target> 
</project> 

load.properties:

prop1=false 
some_other=true 
also_true=yes 
yet_another=on 
not_this=no 

TC_name1=true 
Tc_name2=false 

some_other_match =yes 
not_a_yes= false 

輸出:

Buildfile: build.xml 

load: 
[trueProps] testing.some_other=true 
[trueProps] testing.also_true=yes 
[trueProps] testing.yet_another=on 
[trueProps] testing.TC_name1=true 
[trueProps] testing.some_other_match =yes 
[trueKeys] testing.some_other 
[trueKeys] testing.also_true 
[trueKeys] testing.yet_another 
[trueKeys] testing.TC_name1 
[trueKeys] testing.some_other_match 
[echoproperties] #Ant properties 
[echoproperties] #Wed May 29 10:57:26 EDT 2013 
[echoproperties] testing.TC_name1=true 
[echoproperties] testing.also_true=yes 
[echoproperties] testing.some_other=true 
[echoproperties] testing.some_other_match=yes 
[echoproperties] testing.yet_another=on 

BUILD SUCCESSFUL 
Total time: 0 seconds 
+0

+1適用於無外部插件的解決方案。就我個人而言,我會嵌入一個groovy腳本,但那需要一個外部的jar。 –