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

One thought on “Kotlin – How to write to file with Kotlin language”

  1. I have been exploring for a little for any high-quality articles or weblog posts in this kind of
    space . Exploring in Yahoo I finally stumbled upon this
    website. Reading this info So i am happy to express that I’ve an incredibly good
    uncanny feeling I came upon exactly what I needed. I so much certainly will make certain to
    don?t fail to remember this web site and provides it a look on a relentless basis.

Leave a Reply

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