File I/O in Kotlin - Reading and Writing Files


Working with files is a common task in software development, and Kotlin provides convenient ways to read from and write to files. In this guide, we'll explore how to perform file I/O operations using Kotlin.


Reading from a File

You can read the contents of a file using Kotlin's `readText()` function. Here's a simple example:

import java.io.File
val file = File("example.txt")
if (file.exists()) {
val content = file.readText()
println("File content: $content")
} else {
println("File not found.")
}

In this example, we check if the file exists, and if it does, we read its content using the `readText()` function.


Writing to a File

You can write text to a file using Kotlin's `writeText()` function. Here's a basic example:

import java.io.File
val textToWrite = "Hello, Kotlin!"
val file = File("output.txt")
file.writeText(textToWrite)
println("Data written to file.")

In this example, we write the "Hello, Kotlin!" text to a file named "output.txt."


Working with File Paths

Kotlin's `File` class allows you to work with file paths easily:

import java.io.File
val currentDirectory = System.getProperty("user.dir")
val filePath = File(currentDirectory, "example.txt")
val absolutePath = filePath.absolutePath
println("Current Directory: $currentDirectory")
println("File Path: $absolutePath")

Conclusion

Kotlin provides straightforward methods for performing file I/O operations, making it easy to read from and write to files. Whether you're working with configuration files, data storage, or any file-related task, Kotlin's file handling capabilities simplify the process and enhance the efficiency of your applications.


Happy coding!