Kotlin – Write to File

You can write to a file in Kotlin by using java.io.File extension functions such as writeText(), appendText(), printWriter(), and bufferedWriter(). These examples apply to Kotlin/JVM and Android projects where java.io.File is available.

For small text files, File.writeText() is usually the simplest Kotlin-style option. For repeated writes, large text, or line-by-line output, use bufferedWriter() or printWriter() with use { } so that the writer is closed automatically.

One can write to file in Kotlin using the extension functions provided by Kotlin (or say idiomatic way or Kotlin way) or may also use the existing Java code that writes content to a file.

In this Kotlin Tutorial, we shall go through an example of how to use Java Classes like PrintWriter to write to a file, and more examples using extension functions in Kotlin style.

Choosing the right Kotlin file writing function

Kotlin file writing needRecommended optionNotes
Write one small String and overwrite the fileFile.writeText(content)Simple and readable. Existing file content is replaced.
Add text to the end of an existing fileFile.appendText(content)Creates the file if it does not exist, but does not create missing parent folders.
Write many lines or repeated valuesFile.bufferedWriter().use { }Better for repeated writes because data is buffered before writing to disk.
Use familiar Java-style printing methodsFile.printWriter().use { }Convenient when you want print() and println().
Write binary dataFile.writeBytes(bytes)Use bytes instead of text functions for images, PDFs, and other binary files.

All examples below write to file.txt in the current working directory. In an IDE, the current working directory may be the project folder or a configured run directory. Use an absolute path when you need the file to be created in a specific location.

Example 1 – Write to File with PrintWriter

In this example, we take a string and write it to a file using java.io.PrintWriter. Following are the steps.

  1. Have your data ready as a string in a variable.
  2. Initialize a PrintWriter object.
  3. Append the string to the file using PrintWriter.append() function.
  4. Close the writer.

Kotlin Program – example.kt

</>
Copy
import java.io.PrintWriter

/**
 * Example to use standard Java method in Kotlin to write content to a text file
 */
fun main(args: Array<String>) {
    // content to be written to file
    var content = "Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com."

    // using java class java.io.PrintWriter
    val writer = PrintWriter("file.txt")
    writer.append(content)
    writer.close()
}

A new file with the name file.txt, as specified for the argument of PrintWriter(), shall be created with the content. If the file is already present, the content of the file is cleared first, and then the new content is written into the file.

In new Kotlin code, prefer wrapping writers in use { }. It closes the writer even when an exception occurs while writing.

Example 2 – Write to File with java.io.File.printWriter()

In this example, we shall use Kotlin extension function printWriter to the class java.io.File. Following is the process to write to file.

  1. Have your content as a string.
  2. Pass the file name to the File constructor.
  3. Then call printWriter() on the File.
  4. With use, call the println(content) on the writer which writes the content to the file.

Kotlin Program – example.kt

</>
Copy
import java.io.File

/**
 * Example to use File.printWriter in Kotlin to write content to a text file
 */
fun main(args: Array<String>) {
    // content to be written to file
    var content = "Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com."

    // write content to file
    File("file.txt").printWriter().use { out ->
        out.println(content)
    }
}

println() writes the text followed by a line separator. If you do not want a line separator, use print(content) instead of println(content).

Example 3 – Write to File with java.io.File.bufferedWriter()

Similar to the previous example, we can use java.io.File.bufferedWriter() extension function to get the writer object and then use write() function on the writer object to write content to the file.

Kotlin Program – example.kt

</>
Copy
import java.io.File

/**
 * Example to use File.bufferedWriter() in Kotlin to write content to a text file
 */
fun main(args: Array<String>) {
    // content to be written to file
    var content = "Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com."

    // write content to file
    File("file.txt").bufferedWriter().use { out ->
        out.write(content)
    }
}

bufferedWriter() is a good choice when you are writing multiple values because it reduces frequent direct writes to the file system. Use newLine() when you want to write each value on a separate line.

</>
Copy
File("numbers.txt").bufferedWriter().use { writer ->
    for (number in 1..5) {
        writer.write("Number: $number")
        writer.newLine()
    }
}

Example 4 – Write to File with java.io.File.writeText()

If you are writing exclusively text to a File, then you can use the extension function java.io.File.writeText().

In the following example, we have used this extension function to write some text to a file.

Kotlin Program – example.kt

</>
Copy
import java.io.File

/**
 * Example to use File.writeText in Kotlin to write text to a file
 */
fun main(args: Array<String>) {
    // content to be written to file
    var content = "Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com."

    // write content to file
    File("file.txt").writeText(content)
}

writeText() writes the complete string to the file and replaces the existing file content. The Kotlin standard library uses UTF-8 by default for this function, and you can pass another charset when required.

</>
Copy
import java.io.File
import java.nio.charset.Charset

fun main() {
    val content = "Kotlin file writing with a chosen charset"
    File("file.txt").writeText(content, Charset.forName("UTF-8"))
}

Example 5 – Append text to an existing file in Kotlin

Use appendText() when the new content should be added after the existing file content instead of replacing it.

</>
Copy
import java.io.File

fun main() {
    val logFile = File("app-log.txt")

    logFile.appendText("Application started\n")
    logFile.appendText("User opened the home screen\n")
}

After running the program, the file contains both appended lines. If you run the program again, the same two lines are added again at the end.

Application started
User opened the home screen

Create parent folders before writing a Kotlin file

Kotlin file writing functions can create the target file when it is missing, but they do not automatically create missing parent directories. If your path contains folders that may not exist, create those folders before writing the file.

</>
Copy
import java.io.File

fun main() {
    val file = File("reports/2024/summary.txt")

    file.parentFile?.mkdirs()
    file.writeText("Monthly summary")
}

The safe call parentFile?.mkdirs() avoids a null error when the file path has no parent folder. For production code, check whether the folders were actually created when failure needs to be reported to the user.

Write multiple lines to a file in Kotlin

When your content is stored as a list of strings, you can join the values with System.lineSeparator() and then write the final text. This keeps the line separator suitable for the operating system.

</>
Copy
import java.io.File

fun main() {
    val names = listOf("Arun", "Bhavya", "Charan")
    val content = names.joinToString(separator = System.lineSeparator())

    File("names.txt").writeText(content)
}

For a very large list, prefer bufferedWriter() and write each line inside a loop instead of building one very large string in memory.

Overwrite, append, and charset behavior while writing files in Kotlin

  • writeText() overwrites the existing file content.
  • appendText() adds content to the end of the file.
  • printWriter() and bufferedWriter() overwrite the file when opened in the default way.
  • Text file functions use a character encoding. Use UTF-8 unless your file must match another encoding.
  • File-writing functions may throw exceptions when the path is invalid, permission is missing, or the parent directory does not exist.

Running a Kotlin file writing example from the command line

If the Kotlin command-line compiler is installed, you can compile and run a file writing example like this. The generated file.txt appears in the directory from which the program is run.

</>
Copy
kotlinc example.kt -include-runtime -d example.jar
java -jar example.jar
cat file.txt

Expected text for the examples that write the TutorialKart greeting:

Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com.

Kotlin file writing on JVM, Android, and multiplatform projects

The examples in this tutorial use java.io.File, so they are suitable for Kotlin/JVM and Android code that has access to the file system. In Android apps, write to an app-specific directory or use Android storage APIs according to the type of file and Android version. In Kotlin Multiplatform common code, java.io.File is not available directly, so file writing is usually handled with platform-specific code or a multiplatform file library.

For the official function details, refer to Kotlin standard library documentation for File.writeText().

Common Kotlin file writing mistakes and fixes

MistakeWhat happensFix
Forgetting to close a writerData may not be flushed completely, and resources stay open longer than needed.Use use { } with printWriter() or bufferedWriter().
Using writeText() when append is neededExisting file content is replaced.Use appendText() or open a writer in append mode.
Writing to a folder that does not existThe program can fail with a file-not-found or path-related exception.Create parent folders with parentFile?.mkdirs().
Using text functions for binary filesBinary data can be corrupted because text encoding is applied.Use writeBytes() for binary content.
Assuming the file is created beside the source fileThe file is created in the process working directory instead.Print or configure the working directory, or use an absolute path.

FAQs about writing to a file in Kotlin

What is the simplest way to write text to a file in Kotlin?

The simplest Kotlin/JVM way is File("file.txt").writeText(content). It creates the file if possible and replaces the existing file content.

How do I append text to a file in Kotlin without deleting old content?

Use File("file.txt").appendText(content). Add \n or use a writer with newLine() when each appended value should start on a new line.

Does Kotlin writeText create missing folders automatically?

No. writeText() can create the target file, but missing parent folders must be created separately, for example with file.parentFile?.mkdirs().

When should I use bufferedWriter instead of writeText in Kotlin?

Use bufferedWriter() when you write many lines, large text, or repeated values. It avoids building one large string and closes safely when used with use { }.

Can the same Kotlin file writing code be used in Kotlin Multiplatform common code?

No. The examples that use java.io.File are for Kotlin/JVM and Android. Kotlin Multiplatform common code needs platform-specific file handling or a multiplatform file API.

Kotlin write-to-file editorial QA checklist

  • Check whether each example overwrites or appends, and explain the behavior near the code.
  • Use use { } in writer examples so readers learn automatic closing.
  • State that missing parent directories must be created before writing nested paths.
  • Use language-kotlin for Kotlin code blocks and output for result-only blocks.
  • Clarify that java.io.File examples are for Kotlin/JVM and Android, not common multiplatform code.

Kotlin file writing summary

In this Kotlin Tutorial, we learned to write content to file in Kotlin using standard Java function and also using Kotlin extension functions to java.io.File : printWriter(), bufferedWriter(), writeText(). Use writeText() for simple overwrite operations, appendText() when old content must remain, and bufferedWriter() for repeated or large text writing.