Modifying Property Files with Ant

I was recently testing a Web Service that expected a unique key be passed with each invocation. I could have used the date/time or I could have persisted a counter in a database. Instead, I used the optional ant propertyfile task to persist a counter in a property file.

Here is a simple ant build file demonstrating how to increment a counter in a Java properties file. The propertyfile file attribute specifies the name of the property file and each nested entry element specifies how the value of a property file key should be modified. In this case, the value of the key “count” is treated as an int and the value 1 is added upon each invocation.

1
2
3
4
5
6
7
<project default="run">
<target name="run">
<propertyfile file="test.properties">
<entry key="count" type="int" operation="+" value="1" />
</propertyfile>
</target>
</project>

Here is the build file in operation.

1
1 $ cat test.properties
count=100
2 $ ant run
Buildfile: build.xml

run:
[propertyfile] Updating property file: /Projects/Learn/Ant/propertyfile/test.properties

BUILD SUCCESSFUL
Total time: 0 seconds
3 $ cat test.properties 
#Sun Oct 01 14:11:06 EDT 2006
count=101

The propertyfile entry element also allows us to specify a default value.

1
2
3
4
5
6
7
<project default="run">
<target name="run">
<propertyfile file="test.properties">
<entry key="count" default="10" type="int" operation="+" value="1" />
</propertyfile>
</target>
</project>
1
1 $ rm test.properties
2 $ ant run
Buildfile: build.xml

run:
[propertyfile] Creating new property file: /Projects/Learn/Ant/propertyfile/test.properties

BUILD SUCCESSFUL
Total time: 0 seconds
3 $ cat test.properties 
#Sun Oct 01 14:30:18 EDT 2006
count=11
4 $ ant run
Buildfile: build.xml

run:
[propertyfile] Updating property file: /Projects/Learn/Ant/propertyfile/test.properties

BUILD SUCCESSFUL
Total time: 0 seconds
5 $ cat test.properties 
#Sun Oct 01 14:37:12 EDT 2006
count=12

And finally, another test to show that any keys not explicitly specified are left alone.

1
1 $ cat test.properties 
#Sun Oct 01 14:37:12 EDT 2006
count=12
more=another value
andmore=yet another value
2 $ ant run
Buildfile: build.xml

run:
[propertyfile] Updating property file: /Projects/Learn/Ant/propertyfile/test.properties

BUILD SUCCESSFUL
Total time: 0 seconds
3 $ cat test.properties 
#Sun Oct 01 14:47:09 EDT 2006
andmore=yet another value
more=another value
count=13

18 Apr: More on the Ant PropertyFile task - eliminating the thousands separator with the pattern attribute.

Disclaimer: I don’t claim to be an expert on ant. Please send comments and corrections.