Get values from properties file using Groovy

Solution 1:

It looks to me you complicate things too much.

Here's a simple example that should do the job:

For given test.properties file:

a=1
b=2

This code runs fine:

Properties properties = new Properties()
File propertiesFile = new File('test.properties')
propertiesFile.withInputStream {
    properties.load(it)
}

def runtimeString = 'a'
assert properties."$runtimeString" == '1'
assert properties.b == '2'

Solution 2:

Unless File is necessary, and if the file to be loaded is in src/main/resources or src/test/resources folder or in classpath, getResource() is another way to solve it.

eg.

    def properties = new Properties()
    //both leading / and no / is fine
    this.getClass().getResource( '/application.properties' ).withInputStream {
        properties.load(it)
    }

    //then: "access the properties"
    properties."my.key"

Solution 3:

Had a similar problem, we solved it with:

def content = readFile 'gradle.properties'

Properties properties = new Properties()
InputStream is = new ByteArrayInputStream(content.getBytes());
properties.load(is)

def runtimeString = 'SERVICE_VERSION_MINOR'
echo properties."$runtimeString"
SERVICE_VERSION_MINOR = properties."$runtimeString"
echo SERVICE_VERSION_MINOR