Working with the File System in Kotlin: In Practice

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



Working with the file system is one of the basic tasks in any programming language. In Kotlin, thanks to its concise syntax and powerful extensions of the standard Java library, performing operations with files and directories becomes simple and intuitive.



In this article, we will practically cover the main operations: creating, reading, writing, copying, moving, and deleting files and folders. All examples are written in Kotlin and are ready to use in your projects. The material will be useful for both beginners and experienced developers who want to refresh their knowledge or find optimal solutions for everyday tasks.



Main Classes and Imports



To work with the file system in Kotlin, classes from the java.io package (e.g., File) and java.nio.file (e.g., Path, Files) are used. Modern recommendations favor java.nio.file, as this API is more performant and convenient.



For all examples, we will need the following imports:



import java.io.Fileimport java.nio.file.Pathimport java.nio.file.Pathsimport java.nio.file.Filesimport java.nio.file.StandardCopyOptionimport java.nio.file.StandardOpenOption


Creating a File and Directory



Let's start with the simplest — creating a new file and folder.



// Creating a directoryval dir = File("my_directory")if (!dir.exists()) {    dir.mkdirs() // mkdirs() creates all missing parent directories    println("Directory created: ${dir.absolutePath}")}

// Creating a fileval file = File(dir, "example.txt")if (!file.exists()) { file.createNewFile() println("File created: ${file.absolutePath}")}


Note: mkdirs() creates the entire chain of directories if it doesn't exist. mkdir() only creates the last directory and will return false if the parent folder is missing.



Reading and Writing Files



These are the most common operations. Kotlin offers several elegant ways to work with file contents.



Writing to a File



val path = Paths.get("my_directory/write_example.txt")

// String to writeval content = "Hello, world! This string is written to a file.Second line."

// Simple string writing (overwrites the file)Files.writeString(path, content)

// Writing a list of stringsval lines = listOf("Line 1", "Line 2", "Line 3")Files.write(path, lines)

// Appending to the end of the fileval additionalContent = "Additional line."Files.writeString(path, additionalContent, StandardOpenOption.APPEND)


The Files.writeString() method appeared in Java 11 and is available in Kotlin/JVM. If you need support for older versions, use Files.write() with the encoding specified.



Reading from a File



val path = Paths.get("my_directory/write_example.txt")

// Reading the entire content into a stringval fullContent = Files.readString(path)println("File content:$fullContent")

// Reading into a list of stringsval allLines: List<String> = Files.readAllLines(path)allLines.forEachIndexed { index, line -> println("Line ${index + 1}: $line")}

// Reading using a Stream (for large files)Files.lines(path).use { stream -> stream.forEach { line -> println("Processing line: $line") }}


The .use { ... } construct guarantees the stream is closed after processing, which is especially important when working with large files.



Copying, Moving, and Renaming



These operations are also implemented via java.nio.file.Files.



Copying a File



val source = Paths.get("my_directory/example.txt")val destination = Paths.get("my_directory/backup/example_copy.txt")

Blogs

Book Recommendations