Gradle: Read properties from external file

时光怂恿深爱的人放手 提交于 2020-03-21 20:24:52

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34591069/gradle-read-properties-from-external-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!