Kotlin – How to write to file with Kotlin language

kotlin-write-file-feature-image

This tutorial shows you how to write to File in Kotlin using PrintWriter, BufferedWriter or just File Kotlin extension functions.

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Practice

1. PrintWriter


import java.io.File

fun main(args: Array) {

	val outString: String = "Kotlin\nBe Kotlineer - Be Simple - Be Connective."
	File("kotlin1.txt").printWriter().use { out -> out.println(outString) }
}

Check Result:


Kotlin
Be Kotlineer - Be Simple - Be Connective.

2. BufferedWriter


import java.io.File

fun main(args: Array) {

	val outString: String = "Kotlin\nBe Kotlineer - Be Simple - Be Connective."
	File("kotlin2.txt").bufferedWriter().use { out -> out.write(outString) }
}

Check Result:


Kotlin
Be Kotlineer - Be Simple - Be Connective.

3. File Kotlin extension functions


import java.io.File

fun main(args: Array) {

	val outString: String = "Kotlin\nBe Kotlineer - Be Simple - Be Connective."
	val file = File("kotlin3.txt")

	file.writeText(outString)
	file.appendText("\nMaster Kotlin.")
	file.appendText("\nDo Great Work.")
}

Check Result:


Kotlin
Be Kotlineer - Be Simple - Be Connective.
Master Kotlin.
Do Great Work.

4. When input text is null


import java.io.File

fun main(args: Array) {

	val outString: String? = null

	File("kotlin1.txt").printWriter().use { out -> out.println(outString) }
	// write text: null

	File("kotlin2.txt").bufferedWriter().use { out -> out.write(outString) }
	// compiled but throw java.lang.NullPointerException at runtime

	val file = File("kotlin3.txt")

	file.writeText(outString)
	// not compiled: Type mismatch: inferred type is String? but String was expected
	file.appendText("\nMaster Kotlin.")
	file.appendText("\nDo Great Work.")
}


By grokonez | August 29, 2017.

Last updated on May 7, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*