Kotlin DSL从其他文件中检索密钥 [英] kotlin DSL retrieving keys from other file

查看:147
本文介绍了Kotlin DSL从其他文件中检索密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Gradle文件切换到Kotlin DSL.我的项目正在打电话 API.

I am trying to switch my gradle files to Kotlin DSL. My project is making call to an API.

build.gradle(app)中,我有一个函数来检索存储在另一个数据库中的api密钥 文件keys.properties.

In build.gradle(app) I had a function to retrieve an api key stored in an other file keys.properties.

出现问题后(对于示例)我重写了该函数以获取 钥匙.我在build.gradle.kts中编写了以下函数:

After some problem (for example) I rewrote the function to get the key. I wrote the following function in build.gradle.kts:

import import java.io.File

fun readFileLineByLineUsingForEachLine2(fileName: String): HashMap<String, String>{
    val items = HashMap<String, String>()

    File(fileName).forEachLine {
        items[it.split("=")[0]] = it.split("=")[1]
    }

    return items
}

然后我设置一个变量来保存特定键的值:

Then I set a variable to hold the value of a particular key:

buildConfigField(String!, "API_KEY", returnMapOfKeys()["API_KEY"])

修复了一些错误后,我陷入了以下错误:

After fixing some errors I am stuck with the following one:

app/build.gradle.kts:49:36: Expecting ')'

buildConfigField指向上一行.

有人知道这个错误在哪里吗?

Does someone know where is this error ?

还是有人知道如何使用Kotlin DSL从文件中检索密钥?

Or does someone know how to retrieve keys from files with Kotlin DSL ?

推荐答案

我解决了我的问题(似乎是这样.检查编辑!).我最终得到了以下功能:

I solved my problem (it seems so.. check the edit!!). I ended up with the following function:

// Retrieve key for api
fun getApiKey(): String {
    val items = HashMap<String, String>()
    val f = File("keys.properties")

    f.forEachLine {
        items[it.split("=")[0]] = it.split("=")[1]
    }

    return items["API_KEY"]!!
}

然后我按如下方式呼叫buildConfigField:

And then I call buildConfigField as follow:

buildConfigField("String", "API_KEY", getApiKey())

这部分没有错误了.

一旦我修复了build.gradle.kts中的所有错误,项目的构建就会返回找不到文件keys.properties的信息:我必须修复函数getApiKey.最后,我可以使用以下实现构建并运行我的项目:

Once I have fixed all errors in the build.gradle.kts, the build of my project return that the file keys.properties could not be found: I had to fix my function getApiKey. Finally I could build and run my project with the following implementation:

// Return value of api key stored in `app/keys.properties`
fun getApiKey(): String {
    val items = HashMap<String, String>()

    val fl = rootProject.file("app/keys.properties")

    (fl.exists())?.let {
        fl.forEachLine {
            items[it.split("=")[0]] = it.split("=")[1]
        }
    }

    return items["API_KEY"]!!
}

此功能与其所有硬编码的东西都很好,但是它允许构建我的项目.

This function is far to be good with all its hardcoded stuff but it allows to build my project.

这篇关于Kotlin DSL从其他文件中检索密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆