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 fundamental tasks in software development. Kotlin, being a modern language, offers powerful and concise tools for managing files and directories. Thanks to full compatibility with Java, you can use both classic Java libraries (java.io.File, java.nio.file) and Kotlin extensions, which make the code more readable and safe.



In this article, we will look at the basic operations with the file system in Kotlin: creating, reading, writing, copying, and deleting files and folders. You will learn how to use both standard Java classes and the Kotlin style for writing efficient code.



Main Kotlin Classes and Extensions for Working with Files



Kotlin does not have its own separate library for working with the file system, but it provides many useful extension functions for the java.io.File class. These functions make the code more concise and expressive. The most important ones are listed below:



  • readText() — reads the entire file as a string.
  • readLines() — reads the file line by line and returns a list of strings.
  • writeText() — writes a string to a file (overwrites).
  • appendText() — appends a string to the end of the file.
  • bufferedReader() — returns a BufferedReader for efficient reading.
  • bufferedWriter() — returns a BufferedWriter for efficient writing.
  • inputStream() and outputStream() — for working with binary data.
  • copyTo() — copies a file to another location.
  • deleteRecursively() — recursively deletes a file or directory.


Usage example:

import java.io.File

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

// Writing text to a file file.writeText("Hello, Kotlin!")

// Reading text from a file val content = file.readText() println(content) // Will output: Hello, Kotlin!

// Appending text file.appendText("New line") println(file.readText())}


Using Java NIO (Path and Files)

For more complex operations, such as moving, copying with options, or working with symbolic links, it is recommended to use Java NIO (java.nio.file.Path and java.nio.file.Files). Kotlin also supports these classes without any restrictions.



import java.nio.file.Filesimport java.nio.file.Pathimport java.nio.file.Paths

fun main() { val path: Path = Paths.get("nio_example.txt") val content = "Text for NIO"

// Writing using Files.write Files.write(path, content.toByteArray())

// Reading using Files.readAllLines val lines = Files.readAllLines(path) lines.forEach { println(it) }}


Reading and Writing Files: Best Practices



When working with files, it is important to consider the data size and potential errors (e.g., missing file or access rights). Kotlin provides convenient ways to handle exceptions using use and runCatching.



Reading Large Files

For reading large files (more than a few megabytes), it is not recommended to use readText(), as it loads the entire file into memory. Instead, use stream processing:



import java.io.File

fun readLargeFile(filePath: String) { val file = File(filePath) file.bufferedReader().use { reader -> var line: String? while (reader.readLine().also { line = it } != null) { // Process each line println(line) } }}


The construct

Blogs

Book Recommendations