目前,我的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我在下面发布我自己的解决方案,希望能帮助其他人,如果他们有同样的需求。我不是一个职业选手,所以如果你知道一个更好的方法来做这件事,发布你的解决方案。
发布于 2018-01-09 17:00:04
下面的代码是我发现的工作来完成这个任务。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 + '"')https://stackoverflow.com/questions/48173182
复制相似问题