Working with the File System in Kotlin: From Theory to Practice
\n\nWorking 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\nBasics: Setup and First Steps
\n\nKotlin 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.
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\nThe 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.
Reading and Writing Files in Kotlin
\n\nKotlin offers elegant ways to read and write, eliminating the need to manually manage streams and close resources.
\n\nReading the Entire File Contents
\n\nThe simplest way is to use the readText() function. It reads the entire file into a single string.
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\nIf the file is large, it is better to read it line by line:
\n\nfun 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\nWriting to a File
\n\nFor writing, use writeText() (overwrites the file) or appendText() (appends to the end).
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\nFor more complex data (e.g., writing a list of strings), it is convenient to use writeLines():
fun writeListOfLines() {\n val lines = listOf("Line 1", "Line 2", "Line 3")\n File("list.txt").writeLines(lines)\n}\n\nCreating, Copying, and Deleting Files and Directories
\n\nManaging the file structure is another common task. Let's look at the main operations.
\n\nCreating Files and Folders
\n\nThe 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).
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\nCopying and Moving
\n\nDoes 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.
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