Working with the File System in Kotlin: A Complete 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

Introduction to working with the file system in Kotlin



Working with the file system is one of the basic tasks when developing applications in Kotlin. Whether it's a console application, a server project, or a mobile application for Android, you will almost certainly need to read, write, move, or delete files. Kotlin, being a modern language running on top of the JVM, provides all the capabilities of the standard Java library, but also adds its own convenient extensions and syntactic sugar.



In this article, we will thoroughly examine how to efficiently work with the file system in Kotlin. You will learn how to create and delete files and directories, read and write data, traverse directories, and handle exceptions. All code examples will be written in pure Kotlin without using third-party libraries.



Main classes and approaches



In Kotlin, two main APIs are used for working with the file system:



  • java.io.File — the classic API from Java, which Kotlin extends with its own extension functions.
  • java.nio.file.Path and java.nio.file.Files — a more modern and functional API from Java NIO.


Both approaches are fully compatible with Kotlin, but the second one (NIO) is recommended for new projects, as it provides richer capabilities and better performance.



Creating files and directories



Let's start with the simplest — creating a file. In Kotlin, this is done very concisely:



import java.io.File

fun main() { val file = File("example.txt") // Creating a file (returns true if the file was created) val created = file.createNewFile() if (created) { println("File created: ${file.absolutePath}") } else { println("File already exists") } // Creating a directory val dir = File("myDirectory") val dirCreated = dir.mkdir() // or mkdirs() for creating nested directories println("Directory created: $dirCreated")}


Note the mkdirs() method — it will create all missing parent directories, unlike mkdir(), which only creates the last directory in the path.



Reading files



Kotlin provides elegant extensions for reading file contents. Let's look at several ways:



import java.io.File

fun readExamples() { val file = File("data.txt") // Reading the entire file into a string val content: String = file.readText() println("File contents:$content") // Reading line by line into a list val lines: List<String> = file.readLines() lines.forEach { println("Line: $it") } // Reading all bytes val bytes: ByteArray = file.readBytes() println("File size: ${bytes.size} bytes") // Reading using Buffered (for large files) file.forEachLine { line -> println("Processing line: $line") }}


For large files, it's better to use forEachLine or bufferedReader() to avoid loading the entire file into memory.



Writing to files



Writing data to a file is also intuitive:



import java.io.File

fun writeExamples() { val file = File("output.txt") // Writing a string (overwrites the file) file.writeText("Hello, Kotlin!Second line") // Appending to the end of the file file.appendText("Third line (appended)") // Writing a list of strings val lines = listOf("Line 1", "Line 2", "Line 3") file.writeText(lines.joinToString("")) // Writing bytes val data = byteArrayOf(72, 101, 108, 108, 111) // "Hello" in ASCII file.writeBytes(data)}


If you need more control (for example, to specify an encoding), use

Blogs

Book Recommendations