如果默认属性文件在 Android Gradle Build 中不存在,如何创建它



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

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

错误: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 专业人士,所以如果您知道更好的方法,请发布您的解决方案。

以下代码是我发现可以完成此任务的代码。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 + '"')

最新更新