There are multiple ways to write to a file in Kotlin. We’ll discuss the following two ways:
writeText
methodwriteBytes
methodwriteText()
methodIt’s easier to write to a file using the writeText()
method. It allows us to write a string to a file. The method first encodes the given text to the specified encoding and then internally uses the writeBytes()
method to write to a file.
File.writeText(text: String, charset: Charset = Charsets.UTF_8)
text
: We use this parameter text/string to write to a file.charset
: We use this character set/encoding.import java.io.Filefun main() {val fileName = "file.txt"val myFile = File(fileName)val content = "Educative is the best platform."myFile.writeText(content)println("Written to the file")}
writeBytes()
methodThe writeBytes()
method writes a ByteArray
to the specified file.
File.writeBytes(array: ByteArray)
array
: This is the byte array to write to a file.import java.io.Filefun main() {val fileName = "file.txt"val myFile = File(fileName)val content = "Educative is the best platform."myFile.writeBytes(content.toByteArray())println("Written to the file")}