如何在 Kotlin 中写入文件? [英] How do I write to a file in Kotlin?

查看:75
本文介绍了如何在 Kotlin 中写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎还没有找到这个问题,但是打开/创建文件、写入文件然后关闭文件的最简单、最惯用的方法是什么?查看 kotlin.io 参考和 Java 文档我设法得到了这个:

I can't seem to find this question yet, but what is the simplest, most-idiomatic way of opening/creating a file, writing to it, and then closing it? Looking at the kotlin.io reference and the Java documentation I managed to get this:

fun write() {
    val writer = PrintWriter("file.txt")  // java.io.PrintWriter

    for ((member, originalInput) in history) {  // history: Map<Member, String>
        writer.append("$member, $originalInput
")
    }

    writer.close()
}

这行得通,但我想知道是否有一种正确的"Kotlin 方法可以做到这一点?

This works, but I was wondering if there was a "proper" Kotlin way of doing this?

推荐答案

有点惯用.对于 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}
")
    }
}

如果您希望它在当前运行的操作系统中正确,您也可以使用 out.newLine() 而不是 .如果你一直这样做,你可能会创建一个扩展函数:

Also you can use out.newLine() instead of 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://stackoverflow.com/a/35462184/3679676

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

这篇关于如何在 Kotlin 中写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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