Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over properties from a file?

All my projects and their versions are defined in a properties file like this:

ProjectNameA=0.0.1
ProjectNameB=1.4.2

I'd like to iterate over all the projects, and use their names and versions in an Ant script.

At present I read the entire file using the property task, then iterate over a given list in a for loop like this:

<for list="ProjectNameA,ProjectNameB" param="project">
   <sequential>
    <echo message="@{project} has version ${@{project}}" />
   </sequential>
</for>

How can I avoid the hard-coding of the project names in the for loop? Basically iterate over each line and extract the name and the version of a project as I go.

like image 750
Herr K Avatar asked Jun 16 '10 19:06

Herr K


People also ask

How do you iterate Properties?

Iterating Properties using For-Each loop + Properties's stringPropertyNames() method. The stringPropertyNames() method of the Properties return a set of keys, where the key and its corresponding value are strings.


1 Answers

Seeing as you're already using antcontrib for, how about making use of the propertyselector task:

<property file="properties.txt" prefix="projects."/>
<propertyselector property="projects" match="projects\.(.*)" select="\1"/>

<property file="properties.txt" />
<for list="${projects}" param="project">
    ...
</for>

The idea here is to read the properties once with the projects prefix, and use the resulting set of properties to build a comma-separated list of projects with the propertyselector task. Then the properties are re-read without the prefix, so that your for loop can proceed as before.

like image 79
martin clayton Avatar answered Sep 19 '22 14:09

martin clayton