Kotlin – Create text file

Kotlin – Create text file

To create a text file in Kotlin, you can use File and FileWriter classes of java.io package.

In this tutorial, we shall go through detailed steps to create a text file in Kotlin, and an example program where we create a text file with given filename and file content.

Steps to create a Text file in Kotlin

1. Import libraries

First, make sure to import the required libraries for file handling in Kotlin. We shall use the java.io.File and java.io.FileWriter classes for creating a file.

import java.io.File
import java.io.FileWriter

2. Choose a File Name and Location

Decide on a file name and specify the location where you want to create the text file.

You can provide an absolute or relative path. For this example, we’ll create a file named “example.txt” in the current working directory.

val fileName = "example.txt"
val content = "This is the content of the text file."

3. Create and Write to the Text File

Create a file object using the given filename.

val file = File(fileName)

Create a File writer to write content to file.

val writer = FileWriter(file)

Write content to file.

writer.write(content)

Close the File writer.

writer.close()

Please note that this approach overrides the content if the file already exists.

4. Error Handling

It’s essential to handle exceptions when working with file operations.

Therefore, write all the code that could throw an expiation in a try-catch statement.

try {

} catch (e: Exception) {
    println("An error occurred: ${e.message}")
}

Kotlin Example Program to Create a File

Let us put all the above steps together, and create a file named "example.txt" with some sample text content in the file, in Kotlin.

Main.kt

import java.io.File
import java.io.FileWriter

fun main(args: Array<String>) {
    val fileName = "example.txt" // File name
    val content = "This is the content of the text file."

    try {
        // Create a File object for the specified file name
        val file = File(fileName)

        // Create a FileWriter to write to the file
        val writer = FileWriter(file)

        // Write content to the file
        writer.write(content)

        // Close the FileWriter
        writer.close()

        println("File '$fileName' has been created with given content.")
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    }
}

Output

File 'example.txt' has been created with given content.

The file has been created at the root of the Kotlin project.

Summary

In this Kotlin File Operations tutorial, we have seen how to create a text file with given filename and content using File and FileWriter classes of java.io package, with step by step guide, and an example program.