'Read value from local.properties via Kotlin DSL

I want to retreive key from local.properties file that looks like :

sdk.dir=C\:\\Users\\i30mb1\\AppData\\Local\\Android\\Sdk
key="xxx"

and save this value in my BuildConfig.java via gradle Kotlin DSL. And later get access to this field from my project.



Solution 1:[1]

Okay. I found solutions.

For Android Projects :

  1. In my build.gradle.kts I create a value that retrieves my key:
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties

val key: String = gradleLocalProperties(rootDir).getProperty("key")
  1. And in the block buildTypes I write it:
buildTypes {
 getByName("debug") {
    buildConfigField("String", "key", key)
   }
}
  1. And in my Activity now I can retrieve this value:
override fun onCreate() {
    super.onCreate()
    val key = BuildConfig.key
}

For Kotlin Projects:

  1. We can create an extension that help us to retrieve desired key:
fun Project.getLocalProperty(key: String, file: String = "local.properties"): Any {
    val properties = java.util.Properties()
    val localProperties = File(file)
    if (localProperties.isFile) {
        java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8).use { reader ->
            properties.load(reader)
        }
    } else error("File from not found")

    return properties.getProperty(key)
}
  1. And use this extension when we would like
task("printKey") {
   doLast {
       val key = getLocalProperty("key")
       println(key)
   }
}

Solution 2:[2]

If you don't have access to gradleLocalProperties (it's only accessible for android projects):

val prop = Properties().apply {
    load(FileInputStream(File(rootProject.rootDir, "local.properties")))
}
println("Property:" + prop.getProperty("propertyName"))

Don't forget imports:

import java.io.File
import java.io.FileInputStream
import java.util.*

Solution 3:[3]

put your property in local.properties

and in build.gradle(app).kts file reference it as such: gradleLocalProperties(rootDir).getProperty("YOUR_PROP_NAME")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Michał Klimczak
Solution 3 Jean Raymond Daher