def getLocalProperties() {
Properties localProperties = new Properties()
File file = project.rootProject.file('local.properties')
if (file.exists()) {
//localProperties.load(file.newDataInputStream()) // 会导致中文乱码
localProperties.load(file.newReader("UTF-8")) // 解决 gradle properties 中文乱码
}
return localProperties
}
// get Local Properties
Properties localProperties = getLocalProperties()
println localProperties.get("key1")
println localProperties.get("key2")
解决 gradle properties 中文乱码
完善后的方法:
private Properties localProperties
private Properties readPropertiesIfExist(File propertiesFile) {
Properties result = new Properties()
if (propertiesFile.exists()) {
propertiesFile.withReader('UTF-8') { reader -> result.load(reader) }
}
return result
}
private String resolveProperty(Project project, String name, String defaultValue) {
if (localProperties == null) {
localProperties = readPropertiesIfExist(new File(project.projectDir.parentFile, "local.properties"))
}
String result
if (project.hasProperty(name)) {
result = project.property(name)
}
if (result == null) {
result = localProperties.getProperty(name)
}
if (result == null) {
result = defaultValue
}
return result
}