Working with the File System in Kotlin: A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with the File System in Kotlin: From Theory to Practice

\n\n

Working with the file system is one of the basic tasks every developer encounters. In Kotlin, thanks to its tight integration with Java and its own convenient extensions, managing files and directories becomes intuitive and concise. In this article, we will cover key operations: creating, reading, writing, and deleting files, as well as working with directories. All examples are written in Kotlin and are ready to use in your projects.

\n\n

Basics: Setup and First Steps

\n\n

Kotlin does not have its own separate library for working with the file system — it fully leverages the power of java.io.File, adding many extension functions to it. This means you can use familiar Java methods, but with a shorter and safer syntax.

\n\n
import java.io.File\n\nfun main() {\n    val file = File("example.txt")\n    println(file.exists()) // false if the file does not exist\n}
\n\n

The main class is java.io.File. It represents an abstraction of a path to a file or directory, which does not necessarily have to exist on the disk.

\n\n

Reading and Writing Files in Kotlin

\n\n

Kotlin offers elegant ways to read and write, eliminating the need to manually manage streams and close resources.

\n\n

Reading the Entire File Contents

\n\n

The simplest way is to use the readText() function. It reads the entire file into a single string.

\n\n
fun readEntireFile() {\n    val file = File("data.txt")\n    if (file.exists()) {\n        val content: String = file.readText()\n        println(content)\n    } else {\n        println("File not found")\n    }\n}
\n\n

If the file is large, it is better to read it line by line:

\n\n
fun readLines() {\n    File("log.txt").useLines { lines ->\n        lines.forEach { line ->\n            println(line)\n        }\n    }\n    // useLines will automatically close the stream\n}
\n\n

Writing to a File

\n\n

For writing, use writeText() (overwrites the file) or appendText() (appends to the end).

\n\n
fun writeToFile() {\n    val file = File("output.txt")\n    file.writeText("Hello, Kotlin!\\n")\n    file.appendText("This is the second line.")\n    \n    println(file.readText())\n    // Output:\n    // Hello, Kotlin!\n    // This is the second line.\n}
\n\n

For more complex data (e.g., writing a list of strings), it is convenient to use writeLines():

\n\n
fun writeListOfLines() {\n    val lines = listOf("Line 1", "Line 2", "Line 3")\n    File("list.txt").writeLines(lines)\n}
\n\n

Creating, Copying, and Deleting Files and Directories

\n\n

Managing the file structure is another common task. Let's look at the main operations.

\n\n

Creating Files and Folders

\n\n

The createNewFile() method creates a new empty file if it does not already exist. To create directories, use mkdir() (creates only the last folder in the path) or mkdirs() (creates all missing parent directories).

\n\n
fun createStructure() {\n    val dir = File("my_project/src/main")\n    if (dir.mkdirs()) {\n        println("Directory created: ${dir.absolutePath}")\n    }\n    \n    val newFile = File(dir, "config.ini")\n    if (newFile.createNewFile()) {\n        println("File created: ${newFile.name}")\n    }\n}
\n\n

Copying and Moving

\n\n

Does Kotlin have a built-in copyTo function? Actually, it does! The copyTo() method allows you to easily copy files, and renameTo() allows you to rename or move them.

\n\n
fun copyAndMove() {\n    val source = File("source.txt")\n    val destination = File("backup/source_copy.txt")\n    \n    // Copying\n    source.copyTo(destination, overwrite = true)\n    \n    // Re                

Blogs

Book Recommendations