【问题标题】:How can I create a default properties file if it doesn't exist in Android Gradle Build如果 Android Gradle Build 中不存在默认属性文件,我该如何创建它
【发布时间】:2018-01-09 17:00:04
【问题描述】:

目前,我的 android 项目从本地 properties 文件加载两个参数以填充一些 Build.Config 常量。拥有单独的local.properties 文件的目的是使其不受源代码控制。 (这个文件被 git 忽略了)。其中的值对生产构建没有价值,开发人员可能会经常更改。我不希望这些值的更改构成build.gradle 的更改。我也不希望它仅仅因为开发人员签出不同的 git 分支而改变。

我的问题是,由于此属性文件不在源代码管理中,因此无法构建新的克隆和签出,因为该文件不存在。在文件不存在的情况下,我希望脚本创建它并将默认参数保存到它。

ERROR: C:\Users\Me\AndroidStudioProjects\MyAwesomeApp\app\local.properties(系统找不到指定的文件)

我当前的build.gradle 从属性文件中读取:

Properties properties = new Properties()
properties.load(project.file('local.properties').newDataInputStream())
def spoofVin = properties.getProperty('spoof.vin', '12345678901234567')
def spoofId = properties.getProperty('spoof.id', '999999999999')
buildConfigField("String", "SPOOF_VIN", '"' + spoofVin + '"')
buildConfigField("String", "SPOOF_ID", '"' + spoofId + '"')

示例app/local.properties 文件:

#Change these variables to spoof different IDs and VINs. Don't commit this file to source control.
#Wed Nov 18 12:13:30 CST 2020
spoof.id=999999999999
spoof.vin=12345678901234567

我在下面发布了我自己的解决方案,希望能帮助其他有相同需求的人。我不是 Gradle 专业人士,所以如果您知道更好的方法,请发布您的解决方案。

【问题讨论】:

    标签: android gradle groovy android-gradle-plugin


    【解决方案1】:

    以下代码是我发现的用于完成此任务的代码。 properties.store 方法方便我在 properties.local 文件的顶部添加一个字符串注释。

    //The following are defaults for new clones of the project.
    //To change the spoof parameters, edit local.properties
    def defaultSpoofVin = '12345678901234567'
    def defaultSpoofId = '999999999999'
    def spoofVinKey = 'spoof.vin'
    def spoofIdKey = 'spoof.id'
    
    Properties properties = new Properties()
    File propertiesFile = project.file('local.properties')
    if (!propertiesFile.exists()) {
        //Create a default properties file
        properties.setProperty(spoofVinKey, defaultSpoofVin)
        properties.setProperty(spoofIdKey, defaultSpoofId)
    
        Writer writer = new FileWriter(propertiesFile, false)
        properties.store(writer, "Change these variables to spoof different IDs and VINs. Don't commit this file to source control.")
        writer.close()
    }
    
    properties.load(propertiesFile.newDataInputStream())
    def spoofVin = properties.getProperty(spoofVinKey, defaultSpoofVin)
    def spoofId = properties.getProperty(spoofIdKey, defaultSpoofId)
    buildConfigField("String", "SPOOF_VIN", '"' + spoofVin + '"')
    buildConfigField("String", "SPOOF_ID", '"' + spoofId + '"')
    

    【讨论】:

    • 不错的解决方案。我有同样的要求并寻找解决方案。感谢您发布解决方案。您是否找到任何其他方法或仅使用此解决方案?
    • @KhushbuShah,这对我来说仍然是多年后最好的解决方案。我喜欢它,因为它创建了属性文件,开发人员将有一个现有的模板文件来修改,而不是需要从头开始创建带有密钥的文件。
    猜你喜欢
    • 2017-04-17
    • 2013-06-20
    • 2016-02-11
    • 2014-11-09
    • 2014-07-20
    • 2015-10-31
    • 1970-01-01
    • 2015-07-15
    • 2015-08-13
    相关资源
    最近更新 更多