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

查看:378
本文介绍了如何在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\n")
    }

    writer.close()
}

这行得通,但是我想知道是否有一种正确的"科特林方式来做到这一点?

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}\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://stackoverflow.com/a/35462184/3679676

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

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

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