Introduction to Working with the File System in Kotlin
Working with the file system is one of the basic tasks that every developer encounters. Whether you are writing a console application, a web service, or a mobile app for Android, the ability to read, write, and manage files is an essential skill. In this article, we will thoroughly examine how to work with the file system in Kotlin, using both standard Java tools and modern language features.
Kotlin is a modern, concise, and safe programming language that is fully compatible with Java. This means you can use all the capabilities of java.io and java.nio.file, while writing code that is much shorter and more expressive. The article is intended for beginner developers who are already familiar with the basics of Kotlin syntax.
Main Classes and Methods for Working with Files
Before moving on to practice, let's get acquainted with the key classes you will need for working with the file system in Kotlin:
java.io.File— the main class for representing files and directories.java.nio.file.Path— a modern interface for working with paths.java.nio.file.Files— a utility class with many static methods.java.io.BufferedReaderandjava.io.BufferedWriter— for line-by-line reading and writing.
Kotlin also has its own convenient extensions for the File class, which make the code even simpler. For example, the functions readText(), writeText(), appendText(), and others.
Creating Files and Directories
Let's start with the simplest — creating a file. In Kotlin, this is done in one line:
import java.io.File
fun main() { val file = File("example.txt") file.createNewFile() // creates the file if it does not exist println("File created: ${file.absolutePath}")}Note: createNewFile() returns a Boolean — true if the file was created, and false if it already exists. To create directories, use the mkdir() or mkdirs() method (creates all missing parent folders):
fun main() { val dir = File("myFolder/subFolder") if (dir.mkdirs()) { println("Directory created: ${dir.absolutePath}") } else { println("Failed to create directory") }}Reading Data from a File
There are several ways to read a file in Kotlin. Let's look at the most popular ones.
Reading the Entire File at Once
If the file is small, it is convenient to read its contents into a single string or a list of strings:
fun main() { val file = File("readme.txt") // Reading the entire text into one string val text: String = file.readText() println("File contents:$text") // Reading line by line val lines: List<String> = file.readLines() lines.forEach { println("Line: $it") }}The readText() method returns a string, and readLines() returns a list of strings. Both methods automatically close the file after reading, which is safe and convenient.
Line-by-Line Reading with Buffering
For large files, it is better to use BufferedReader to avoid loading the entire file into memory:
fun main() { val file = File("large_file.txt") file.bufferedReader().use { reader -> var line: String? while (reader.readLine().also { line = it } != null) { println("Reading: $line") } }}The .use { } construct guarantees that the resource will be closed after the block finishes executing, even if an exception occurs.