Kotlin – Create an Empty Text File

Kotlin – Create an Empty Text File

To create an empty text file in Kotlin, you can use the createNewFile() method in File class from the java.io package. The method creates a new file if it doesn’t already exist.

In this tutorial, we will go through a step by step process of creating an empty text file in Kotlin, with an example.

Steps to Create an Empty Text File in Kotlin

To create an empty 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 createNewFile() method to create a new, empty file. This method returns true if the file is created successfully and false if the file already exists.

Kotlin Example Program to Create an Empty Text File

In the following example program, we will create an empty file named 'newfile.txt'.

Main.kt

import java.io.File

fun main() {
    val filePath = "example.txt" // Replace with your file path
    val file = File(filePath)

    val result = file.createNewFile()
    if (result) {
        println("File created successfully: ${file.absolutePath}")
    } else {
        println("File already exists.")
    }
}

Output

File created successfully: /Users/kotlinandroid/IdeaProjects/KotlinApp/example.txt

If you have given a file, that already exists, you would get the following output.

File created successfully: [absolute file path]

The output will indicate whether a new file was created or if it already existed.

Summary

In this Kotlin tutorial, we covered how to create a new, empty text file using File.createNewFile() method, with an example.