Kotlin – Write String to Text File

Kotlin – Write String to Text File

To write a string to a text file in Kotlin, you can use the File class from the java.io package and its writeText() method. This method allows you to write a string directly to a file, creating the file if it doesn’t already exist or overwriting its content if it does.

In this tutorial, we will go through a step by step process to write a string to a text file in Kotlin, with an example.

Steps to Write a String to a Text File in Kotlin

To write a string to a text file in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object with the desired file path and name.
  3. Use the writeText() method to write a string to the file. This method will create the file if it doesn’t exist or overwrite it if it does.

Kotlin Example Program to Write a String to a Text File

In the following example program, we will write a simple string to a file named 'output.txt'.

Main.kt

import java.io.File

fun main() {
    val filePath = "output.txt" // Replace with the desired file path
    val file = File(filePath)
    val textToWrite = "Hello, Kotlin!"

    file.writeText(textToWrite)
    println("Text written to file successfully.")
}

Output

Text written to file successfully.

The output will confirm that the text has been written to the file.

Kotlin - Write String to Text File

Summary

In this Kotlin tutorial, we explored how to write a string to a text file. This method is essential in many applications where you need to save textual data to a file for storage or later use.