Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin

How to write to a file in Kotlin

abhilash

Overview

There are multiple ways to write to a file in Kotlin. We’ll discuss the following two ways:

  1. The writeText method
  2. The writeBytes method

The writeText() method

It’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.

Syntax

File.writeText(text: String, charset: Charset = Charsets.UTF_8)

Parameter

  • text: We use this parameter text/string to write to a file.
  • charset: We use this character set/encoding.

Code

import java.io.File

fun main() {

    val fileName = "file.txt"
    val myFile = File(fileName)

    val content = "Educative is the best platform."

    myFile.writeText(content)

    println("Written to the file")
}
Using writeText to write to a file

The writeBytes() method

The writeBytes() method writes a ByteArray to the specified file.

Syntax

File.writeBytes(array: ByteArray)

Parameter

  • array: This is the byte array to write to a file.

Code

import java.io.File

fun 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")
}
Using writeBytes to write to a file

RELATED TAGS

kotlin
RELATED COURSES

View all Courses

Keep Exploring