提问人:Tommy 提问时间:10/13/2023 更新时间:10/14/2023 访问量:59
如何在kotlin中将.txt资产转换为ArrayList<String>格式?
How to convert .txt asset to ArrayList<String> format in kotlin?
问:
所以我有数千个坐标需要绘制,我知道的最好的方法之一是将坐标保存为资产文件夹中的 .txt,然后使用
val json_string = application.assets.open(file_name).bufferedReader().use{it.readText()}
但是,当文件被拉取时,它会将文件读取为字符串,尽管文件以数组格式保存,如下所示:
"97.951476367000055,3.155017079000061","97.951800004000063,3.154406602000051","97.949325673000033,3.156145963000029","97.948721732000081,3.15657051200003","97.948646156000052,3.156623638000042","97.947494978000066,3.15786896100002","97.94724135000007,3.158143331000076","97.947000011000057,3.158404405000056","97.946790649000036,3.158630887000072","97.946272953000062,3.15919092200005","97.945702608000033,3.15980791000004","97.945553326000038,3.159969400000023","97.944601930000033,3.160998592000055","97.944409762000078,3.161206474000039"....
我想以数组格式读取资产,例如,它用逗号分隔并按引号分组,例如:
- "97.951476367000055,3.155017079000061"
- "97.951800004000063,3.154406602000051"
- "97.949325673000033,3.156145963000029"
- 等等......
如何在 Kotlin 中将此.txt文件资产读取为字符串数组或 ArrayList< 字符串>格式?
谢谢!
答:
1赞
Amardurai
10/13/2023
#1
创建一个模型,如下所示
data class Coordinate(val latitude: String, val longitude: String)
从资产文件中读取坐标并转换为 ArrayList 的函数
fun readCoordinatesFromAsset(context: Context, assetFileName: String):
ArrayList<String> {
val gson = Gson()
val arrayList = ArrayList<String>()
try {
context.assets.open(assetFileName).use { inputStream ->
val reader = InputStreamReader(inputStream)
val coordinates = gson.fromJson(reader, ArrayList::class.java)
// Convert the ArrayList of Coordinate objects to an ArrayList of strings
for (coordinate in coordinates) {
arrayList.add(coordinate.toString())
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return arrayList
}
您的文本文件应采用以下格式
坐标.txt
[
"97.951476367000055,3.155017079000061",
"97.951800004000063,3.154406602000051",
"97.949325673000033,3.156145963000029",
"97.948721732000081,3.15657051200003",
"97.948646156000052,3.156623638000042",
"97.947494978000066,3.15786896100002",
"97.94724135000007,3.158143331000076",
"97.947000011000057,3.158404405000056",
"97.946790649000036,3.158630887000072",
"97.946272953000062,3.15919092200005",
"97.945702608000033,3.15980791000004",
"97.945553326000038,3.159969400000023",
"97.944601930000033,3.160998592000055",
"97.944409762000078,3.161206474000039"
]
可以将该方法调用为
val resulArray: ArrayList<String> =readCoordinatesFromAsset(this,"coordinate.txt")
评论
0赞
Tommy
10/14/2023
它工作顺利!伟大!
0赞
Meet Miyani
10/14/2023
#2
你可以尝试这样的事情,见下面的代码。
https://pl.kotl.in/NQQdTW6m4?theme=darcula
单击上面的链接来测试和运行代码,您也可以定义自己的模型类,而不是我在本例中用来演示的 Pair()。
随意改进它!
评论
split()
根据分隔符将字符串划分为子字符串。despite the file is saved in array format such as follow:
这不是数组格式。它只是一行带有逗号分隔值的文本行。你最好用线条制作一个 csv/txt 文件。每个位置都有一条线。而且它也不是 json 字符串。