gpt4 book ai didi

android - 如何使用 Kotlin 从 android 中的 Assets 中读取 json 文件?

转载 作者:行者123 更新时间:2023-12-02 13:20:37 27 4
gpt4 key购买 nike

我已经使用过 java,但发现使用 Kotlin 很困难。

我已经用谷歌搜索过,但它们都不适合我。

/**
* Get the json data from json file.
*
* @param context the context to acces the resources.
* @param fileName the name of the json file
* @return json as string
*/
public static String getJsonFromAsset(Context context, String fileName) {
String json = "";
try {
InputStream stream = context.getAssets().open(fileName);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
json = new String(buffer, "UTF-8");

} catch (Exception e) {
e.printStackTrace();
}
return json;
}

我想要 Kotlin 中的这段代码。

最佳答案

从 Kotlin 的 assets 文件夹中读取 json 文件非常简单,只需使用以下代码

val fileInString: String =
applicationContext.assets.open(fileName).bufferedReader().use { it.readText() }

关于android - 如何使用 Kotlin 从 android 中的 Assets 中读取 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com