bigdestroyer bigdestroyer - 2 months ago 22
Android Question

Gradle: Read properties from external file

I have created a file

version.properties
in my Android project that contains this data:

version.code=1
version.name="1.0.0"


And now I want to use this properties in
build.gradle
file this way:

android {

...
defaultConfig {
...
versionCode project.property('version.code')
versionName project.property('version.name')
}
...
}


But, obviously, it doesn't find the properties. How can I add this file to classpath so that I can use its properties?

Answer

To read values from a generic properties file you can use something like this:

def Properties props = new Properties()
def propFile = file('../version.properties')   //pay attention to the path
def versionCode;
if (propFile.canRead()){
    props.load(new FileInputStream(propFile))

    if (props!=null && props.containsKey('version.code') && props.containsKey('version.name')) {

        versionCode = props['version.code']
        ....

   }
}

Using the standard gradle.properties you can do:

VERSION_NAME=1.2.1

Then in your build.gradle you can use:

versionName project.VERSION_NAME

Another way is to set these values in a .gradle file (for example in your top-level file)

ext {
  myVersionCode =  ...
  myVersionName =  ...
}

Then in your module/build.gradle file you can do:

versioneCode   rootProject.ext.myVersionCode