Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Héctor Avatar asked Jan 04 '16 12:01

Héctor


1 Answers

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
like image 114
Gabriele Mariotti Avatar answered Oct 20 '22 14:10

Gabriele Mariotti