gpt4 book ai didi

kotlin - Kotlin从txt.file读取/导入 map

转载 作者:行者123 更新时间:2023-12-02 13:41:15 25 4
gpt4 key购买 nike

我正在做一个学习项目,该项目应该将抽认卡导入和导出到txt.file,以后再用于提问。
目前,我还停留在导入方面,而我所做的研究并没有真正起作用,因为我没有真正了解它。
我在这张总 map 上保存了术语: map 中的定义

private var flashCardMap = mutableMapOf<String, String>()
然后我有这个导出功能
    private fun export() {
println("File name:")
scan.nextLine()
val fileName = scan.nextLine()
val myFile = File(fileName)
try {
myFile.bufferedWriter().use { out->
flashCardMap.forEach {
out.write("${it.key}:${it.value}\n")
} }
println("${flashCardMap.size} cards have been saved.")
} catch (e: FileNotFoundException) {
println("File not Found.")
}
}
它将我之前定义的所有卡导出为txt。带有一个或多个抽认卡的此类文件(卡=定义)
key:value
这就是我被困住的地方。我尝试导入.txt文件和包含 map ,但是它不起作用。它应该导入 map ,并告诉我要导入多少张卡,并将它们添加到我在本次 session 中使用的当前Flashcardmap中。这是我尝试过的:
    private fun import() {
println("File name:")
scan.nextLine()
val fileName = scan.nextLine()
val myFile = File("$fileName")
try {
val importMap =
myFile.readLines().chunked(2) {
it[0] to it[1]
}.toMap()
println("${importMap.size} cards have been loaded.")
flashCardMap.putAll(importMap)
} catch (e: FileNotFoundException) {
println("File not Found.")
}
}

最佳答案

实际上,有很多方法可以将结构化数据序列化到文件中,但是由于您的示例使用的key:value格式(由换行符分隔),我们将继续使用。
该类(class)应适合您的需求。但这非常简单,并且缺乏任何类型的错误处理。

class Serializer(private val filePath: Path, private val delimiter: String = ":") {

fun export(data: Map<String, String>) {
filePath.toFile().writer().use { writer ->
for ((key, value) in data) {
writer.write("$key$delimiter$value\n")
}
}
}

fun import(): Map<String, String> {
val data = mutableMapOf<String, String>()

filePath.toFile().reader().use { reader ->
reader.forEachLine { line ->
val (key, value) = line.split(delimiter)
data[key] = value
}
}

return data
}
}
如果您想利用成熟的格式,则内置的 java.util.Properties类可以使事情变得更加简单。唯一的问题是它默认使用 =分隔符,但它也应该能够读取 :分隔符。
class PropertiesSerializer(private val filePath: Path) {

fun export(data: Map<String, String>) {
val props = Properties()

for ((key, value) in data) {
props[key] = value
}

filePath.toFile().outputStream().use { stream ->
props.store(stream, null)
}
}

fun import(): Map<String, String> {
val props = Properties()

filePath.toFile().inputStream().use { stream ->
props.load(stream)
}

return props
.map { (key, value) -> key.toString() to value.toString() }
.toMap()
}
}

关于kotlin - Kotlin从txt.file读取/导入 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63283193/

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