Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write to a file in Kotlin?

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?

like image 210
yiwei Avatar asked Feb 16 '16 22:02

yiwei


People also ask

How can I write to a file in Android?

This example demonstrates how to create text file and insert data to that file on Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


2 Answers

A bit more idiomatic. For PrintWriter, this example:

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

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.

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

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")     } } 

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() } 

And then use that instead:

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

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

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

like image 74
7 revs, 2 users 99% Avatar answered Sep 20 '22 16:09

7 revs, 2 users 99%


Other fun variations so you can see the power of Kotlin:

A quick version by creating the string to write all at once:

File("somefile.txt").writeText(history.entries.joinToString("\n") { "${it.key}, ${it.value}" }) // or just use the toString() method without transform: File("somefile.txt").writeText(x.entries.joinToString("\n")) 

Or assuming you might do other functional things like filter lines or take only the first 100, etc. You could go this route:

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

Or given an Iterable, allow writing it to a file using a transform to a string, by creating extension functions (similar to writeText() version above, but streams the content instead of materializing a big string first):

fun <T: Any> Iterable<T>.toFile(output: File, transform: (T)->String = {it.toString()}) {     output.bufferedWriter().use { out ->         this.map(transform).forEach { out.write(it); out.newLine() }     } }  fun <T: Any> Iterable<T>.toFile(outputFilename: String, transform: (T)->String = {it.toString()}) {     this.toFile(File(outputFilename), transform) } 

used as any of these:

history.entries.toFile(File("somefile.txt")) {  "${it.key}, ${it.value}" }  history.entries.toFile("somefile.txt") {  "${it.key}, ${it.value}" } 

or use default toString() on each item:

history.entries.toFile(File("somefile.txt"))   history.entries.toFile("somefile.txt")  

Or given a File, allow filling it from an Iterable, by creating this extension function:

fun <T: Any> File.fillWith(things: Iterable<T>, transform: (T)->String = {it.toString()}) {     this.bufferedWriter().use { out ->         things.map(transform).forEach { out.write(it); out.newLine() }     } } 

with usage of:

File("somefile.txt").fillWith(history.entries) { "${it.key}, ${it.value}" } 

or use default toString() on each item:

File("somefile.txt").fillWith(history.entries)  

which if you had the other toFile extension already, you could rewrite having one extension call the other:

fun <T: Any> File.fillWith(things: Iterable<T>, transform: (T)->String = {it.toString()}) {     things.toFile(this, transform) } 
like image 21
4 revs Avatar answered Sep 22 '22 16:09

4 revs