Create a File in Kotlin

Kotlin programs can create files using the java.io.File class or the newer java.nio.file.Path APIs. The appropriate method depends on whether you need an empty file, want to write text or bytes immediately, or must avoid overwriting an existing file.

  • File.createNewFile() creates an empty file only when it does not already exist.
  • File.writeText() creates a file and writes text, replacing existing content.
  • File.writeBytes() creates a file and writes binary data, replacing existing content.
  • Path.createFile() creates an empty file and throws an exception if it already exists.

Relative paths such as data.txt are resolved from the program’s current working directory. Use an absolute path when the file must be created in a specific location.

Create an Empty Kotlin File with File.createNewFile()

File.createNewFile() attempts to create an empty file. It returns true when a new file is created and false when a file with the same path already exists. It does not overwrite an existing file.

The parent directory must already exist. The method can also throw an IOException when the path is invalid, access is denied, or another file-system error occurs.

File.createNewFile() example

The following program tries to create data.txt twice. The first call creates the file, while the second call reports that it already exists.

Main.kt

</>
Copy
import java.io.File

fun main(args: Array<String>) {

    val fileName = "data.txt"

    var file = File(fileName)

    // create a new file
    val isNewFileCreated :Boolean = file.createNewFile()

    if(isNewFileCreated){
        println("$fileName is created successfully.")
    } else{
        println("$fileName already exists.")
    }

    // try creating a file that already exists
    val isFileCreated :Boolean = file.createNewFile()

    if(isFileCreated){
        println("$fileName is created successfully.")
    } else{
        println("$fileName already exists.")
    }

}

Output

data.txt is created successfully.
data.txt already exists.

Create Parent Directories Before Creating a Kotlin File

Creating a file does not automatically create missing parent directories. Call mkdirs() on the parent directory before creating a nested file.

</>
Copy
import java.io.File

fun main() {
    val file = File("reports/2026/data.txt")

    file.parentFile?.mkdirs()

    if (file.createNewFile()) {
        println("Created: ${file.absolutePath}")
    } else {
        println("File already exists: ${file.absolutePath}")
    }
}

mkdirs() creates every missing directory in the path. Check its result separately when your application must distinguish a directory-creation failure from an existing directory.

Create a Kotlin File and Write Text with File.writeText()

File.writeText() creates the target file when it does not exist and writes the supplied string. UTF-8 is used by default, although another character set can be supplied as an argument.

Existing content is replaced. Use this method only when overwriting the file is intended. Passing an empty string creates or truncates the file to zero bytes.

File.writeText() example

In this example, File.writeText() creates an empty file.

Main.kt

</>
Copy
import java.io.File

fun main(args: Array<String>) {

    val fileName = "data.txt"

    var file = File(fileName)

    // create a new file
    file.writeText("")

}

The empty string creates an empty file. To create the file with content, pass the required text instead, such as file.writeText("Kotlin file example").

Create a text file only if it does not exist

An existence check can make the intended behavior clear, but it is not atomic: another process could create the file between the check and the write. For strict create-only behavior, use createNewFile() or Path.createFile() first.

</>
Copy
import java.io.File

fun main() {
    val file = File("notes.txt")

    if (!file.exists()) {
        file.writeText("First note\n")
        println("File created")
    } else {
        println("File already exists; content was not changed")
    }
}

Create a Kotlin File and Write Bytes with File.writeBytes()

File.writeBytes() creates a file when necessary and writes the supplied ByteArray. It is suitable for binary data such as an encoded image or downloaded file. An empty byte array creates or truncates the file to zero bytes.

Existing content is replaced. Do not use writeBytes() when the current file contents must be preserved.

File.writeBytes() example

This example uses an empty ByteArray to create an empty file.

Main.kt

</>
Copy
import java.io.File

fun main(args: Array<String>) {

    val fileName = "data.txt"

    var file = File(fileName)

    // create a new file
    file.writeBytes(ByteArray(0))
}

Replace ByteArray(0) with the byte array that the application needs to store when creating a file with binary content.

Create a File with Kotlin Path.createFile()

Kotlin’s kotlin.io.path extensions provide a concise interface to Java NIO paths. Path.createFile() creates a new empty file and fails with FileAlreadyExistsException if the path already exists.

</>
Copy
import java.nio.file.FileAlreadyExistsException
import kotlin.io.path.Path
import kotlin.io.path.createFile

fun main() {
    val path = Path("data.txt")

    try {
        path.createFile()
        println("Created: $path")
    } catch (exception: FileAlreadyExistsException) {
        println("File already exists: $path")
    }
}

This approach is useful when the application already works with Path objects or needs create-only behavior that reports an existing file as an exception.

Append Text Without Replacing the Kotlin File

Use appendText() when new text should be added after the existing content. It creates the file if it is missing and preserves the current content when the file already exists.

</>
Copy
import java.io.File

fun main() {
    val logFile = File("application.log")

    logFile.appendText("Application started\n")
    logFile.appendText("Configuration loaded\n")
}

Include a newline character when each appended value should begin on a separate line.

Handle Kotlin File-Creation Errors

File operations can fail because a parent directory is missing, the application lacks permission, the path refers to a directory, the storage device is full, or another file-system error occurs. Catch IOException when the application can recover or provide a useful error message.

</>
Copy
import java.io.File
import java.io.IOException

fun main() {
    val file = File("data.txt")

    try {
        if (file.createNewFile()) {
            println("Created ${file.absolutePath}")
        } else {
            println("The file already exists")
        }
    } catch (exception: IOException) {
        println("Could not create the file: ${exception.message}")
    }
}

Create Files in Kotlin for Android

Android applications should create files in an app-specific directory or use the appropriate Android storage API. A relative desktop-style path such as File("data.txt") does not select a reliable Android storage location.

Inside an Android Context, filesDir identifies the app’s internal files directory:

</>
Copy
val file = File(filesDir, "data.txt")
file.writeText("Stored in internal app storage")

Internal app storage does not require a storage permission and is intended for files owned by the application. For user-selected documents or shared media, use Android’s document and media storage APIs instead of constructing arbitrary shared-storage paths.

Choosing a Kotlin File-Creation Method

RequirementKotlin methodExisting file behavior
Create an empty file without overwritingFile.createNewFile()Returns false
Create an empty NIO filePath.createFile()Throws FileAlreadyExistsException
Create a file and write textFile.writeText()Replaces content
Create a file and write binary dataFile.writeBytes()Replaces content
Create a file or add text to itFile.appendText()Preserves and appends to content

Kotlin Create File FAQs

How do I create a Kotlin file only if it does not exist?

Use File.createNewFile(). It creates an empty file and returns true, or returns false without changing an existing file. With a Path, use createFile() and handle FileAlreadyExistsException.

Does File.writeText() create a missing file in Kotlin?

Yes. writeText() creates the file if it is missing. If the file already exists, the method replaces its current content.

How do I append to a file in Kotlin?

Call File.appendText() for text or File.appendBytes() for bytes. These methods add data after the existing content and create the file when it does not exist.

Why does Kotlin fail to create a file in a nested directory?

The parent directories probably do not exist, or the program cannot write to them. Create missing parents with file.parentFile?.mkdirs() and verify that the selected location is writable.

Where is a relative Kotlin file created?

A relative path is resolved from the process’s current working directory. Print file.absolutePath to see the resolved location.

Kotlin File-Creation QA Checklist

  • Confirm whether an existing file must be preserved, replaced, or appended to.
  • Verify that all required parent directories exist before creating a nested file.
  • Check the resolved absolute path when using a relative filename.
  • Handle IOException or specific NIO exceptions where file creation can fail.
  • Use an Android app-specific directory or Android storage API for Android projects.

Summary of Creating Files in Kotlin

In this Kotlin Tutorial, we created empty files with File.createNewFile() and Path.createFile(), created files containing text or bytes with writeText() and writeBytes(), created missing parent directories, appended text without overwriting existing content, and handled common file-system errors.