且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Kotlin中写入文件?

更新时间:2023-09-28 09:28:58

有点惯用语.对于PrintWriter,此示例:

A bit more idiomatic. For PrintWriter, this example:

File("somefile.txt").printWriter().use { out ->
    history.forEach {
        out.println("${it.key}, ${it.value}")
    }
}

for循环或forEach取决于您的样式.没有理由使用append(x),因为它基本上是write(x.toString()),并且您已经给了它一个字符串.并且println(x)在将null转换为"null"之后基本上执行write(x).然后println()做正确的行结尾.

The for loop, or forEach depends on your style. No reason to use append(x) since that is basically write(x.toString()) and you already give it a string. And println(x) basically does write(x) after converting a null to "null". And println() does the correct line ending.

如果您正在使用Kotlin的data类,则可以将它们输出,因为它们已经具有不错的toString()方法.

If you are using data classes of Kotlin, they can already be output because they have a nice toString() method already.

此外,在这种情况下,如果您想使用BufferedWriter,它将产生相同的结果:

Also, in this case if you wanted to use BufferedWriter it would produce the same results:

File("somefile.txt").bufferedWriter().use { out ->
    history.forEach {
        out.write("${it.key}, ${it.value}\n")
    }
}

如果您希望out.newLine()对于运行它的当前操作系统是正确的,则可以使用out.newLine()代替\n.而且,如果您一直在这样做,则可能会创建一个扩展功能:

Also you can use out.newLine() instead of \n if you want it to be correct for the current operating system in which it is running. And if you were doing that all the time, you would likely create an extension function:

fun BufferedWriter.writeLn(line: String) {
    this.write(line)
    this.newLine()
}

然后改用它:

File("somefile.txt").bufferedWriter().use { out ->
    history.forEach {
        out.writeLn("${it.key}, ${it.value}")
    }
}

Kotlin就是这样滚动的.更改API中的内容,使它们符合您的期望.

And that's how Kotlin rolls. Change things in API's to make them how you want them to be.

与此完全不同的是另一个答案: https://***.com/a/35462184/3679676

Wildly different flavours for this are in another answer: https://***.com/a/35462184/3679676