This tutorial shows you ways to write to File in Kotlin using PrintWriter
, BufferedWriter
or Kotlin extension functions such as writeText()
or write()
. You’ll also know how to write Kotlin objects/JSON to a file.
Related Posts:
– How to read File in Kotlin
– Kotlin – Convert object to/from JSON string using Gson
Contents
Overview
Here are several ways to write to a file in Kotlin:
BufferedWriter
anduse()
functionPrintWriter
anduse()
functionFile.writetext()
functionFile.writeBytes()
functionFiles.write()
function
Using BufferedWriter
java.io.File provides bufferedWriter() method that returns a new BufferedWriter object.
We’re gonna call use method to write to file by executes the block function and closes it.
File(name).bufferedWriter().use { out ->
out.write(text)
out.write(nextText)
}
For example:
package com.bezkoder.kotlin.writefile
import java.io.File
fun main(args: Array<String>) {
val outStr1: String = "Bezkoder\nProgramming Tutorials"
val outStr2: String = "Becoming zKoder..."
File("bezkoder1.txt").bufferedWriter().use { out ->
out.write(outStr1)
out.write("\n")
out.write(outStr2)
}
Check bezkoder1.txt file:
Bezkoder
Programming Tutorials
Becoming zKoder...
Using PrintWriter
You can use java.io.File
printWriter() method that returns a new PrintWriter object. PrintWriter prints formatted representations of objects to a text-output stream.
We also need to call use
method for executing the block function.
With PrintWriter
, we can use println()
function so that it’s helpful to write line by line.
File(name).printWriter().use { out ->
out.println(line1)
out.println(line2)
}
For example:
package com.bezkoder.kotlin.writefile
import java.io.File
fun main(args: Array<String>) {
val outStr1: String = "Bezkoder\nProgramming Tutorials"
val outStr2: String = "Becoming zKoder..."
File("bezkoder2.txt").printWriter().use { out ->
out.println(outStr1)
out.println(outStr2)
}
Check bezkoder2.txt file:
Bezkoder
Programming Tutorials
Becoming zKoder...
Using File writeText function
java.io.File has writeText() that sets the content of file as text (UTF-8) or you can specify charset in the second parameter. Using writeText()
will override the existing file.
To append text to existing file, use appendText().
val myFile = File(name)
myFile.writeText(text)
myFile.appendText(nextText)
For example:
package com.bezkoder.kotlin.writefile
import java.io.File
fun main(args: Array<String>) {
val outStr1: String = "Bezkoder\nProgramming Tutorials"
val outStr2: String = "Becoming zKoder..."
val myFile = File("bezkoder3.txt")
myFile.writeText(outStr1)
myFile.appendText("\n" + outStr2)
Check bezkoder3.txt file:
Bezkoder
Programming Tutorials
Becoming zKoder...
Using File writeBytes function
Instead of write with Text, we can write array of bytes to a file using writeBytes().
Kotlin also provides appendBytes() function to append array of bytes to the content of existing file.
val myFile = File(name)
myFile.writeBytes(bytesArray)
myFile.appendBytes(nextBytesArray)
For example:
package com.bezkoder.kotlin.writefile
import java.io.File
fun main(args: Array<String>) {
val outStr1: String = "Bezkoder\nProgramming Tutorials"
val outStr2: String = "Becoming zKoder..."
val file2 = File("bezkoder4.txt")
file2.writeBytes(outStr1.toByteArray())
file2.appendBytes(("\n" + outStr2).toByteArray())
Check bezkoder4.txt file:
Bezkoder
Programming Tutorials
Becoming zKoder...
Using Files write function
java.nio.file.Files provides static method write() that Writes bytes to a file.
There is options
parameter to specify how the file is created or opened.
Files.write(path, bytes, StandardOpenOption.CREATE_NEW);
Files.write(path, bytes, StandardOpenOption.APPEND);
You can find more options here: StandardOpenOption
For example:
package com.bezkoder.kotlin.writefile
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardOpenOption
fun main(args: Array<String>) {
val outStr1: String = "Bezkoder\nProgramming Tutorials"
val outStr2: String = "Becoming zKoder..."
val myfile = File("bezkoder5.txt")
Files.write(myfile.toPath(), outStr1.toByteArray(), StandardOpenOption.CREATE_NEW)
Files.write(myfile.toPath(), ("\n" + outStr2).toByteArray(), StandardOpenOption.APPEND)
}
Check bezkoder5.txt file:
Bezkoder
Programming Tutorials
Becoming zKoder...
Kotlin write JSON to file
Now we have a Tutorial
class like this:
package com.bezkoder.kotlin.writefile
class Tutorial(
val title: String,
val author: String,
val categories: List<String>
) {
override fun toString(): String {
return "Category [title: ${this.title}, author: ${this.author}, categories: ${this.categories}]"
}
}
What if we want to write List<Tutorial>
to JSON file?
There are two steps:
- use
Gson
to convert Kotlin object to JSON string - write the string to JSON file
If you want to make pretty JSON string, GsonBuilder
will help you.
Let’s do it right now.
package com.bezkoder.kotlin.writefile
import java.io.File
import com.google.gson.Gson
import com.google.gson.GsonBuilder
fun main(args: Array<String>) {
val tutsList: List<Tutorial> = listOf(
Tutorial("Tut #1", "bezkoder", listOf("cat1", "cat2")),
Tutorial("Tut #2", "zkoder", listOf("cat3", "cat4"))
);
val gson = Gson()
val jsonTutsList: String = gson.toJson(tutsList)
File("bezkoder1.json").writeText(jsonTutsList)
val gsonPretty = GsonBuilder().setPrettyPrinting().create()
val jsonTutsListPretty: String = gsonPretty.toJson(tutsList)
File("bezkoder2.json").writeText(jsonTutsListPretty)
}
bezkoder1.json
[{"title":"Tut #1","author":"bezkoder","categories":["cat1","cat2"]},{"title":"Tut #2","author":"zkoder","categories":["cat3","cat4"]}]
bezkoder2.json
[
{
"title": "Tut #1",
"author": "bezkoder",
"categories": [
"cat1",
"cat2"
]
},
{
"title": "Tut #2",
"author": "zkoder",
"categories": [
"cat3",
"cat4"
]
}
]
For more details about how to convert Kotlin objects/list/map to JSON and vice versa, please visit:
Kotlin – Convert object to/from JSON string using Gson
Conclusion
Today we’ve known many ways to write content to a file in Kotlin using java.io.File. You can write line by line or entire content at once.
We also have a tutorial for reading File:
How to read File in Kotlin
Happy Learning! See you again.