Reading text files is a common task when you're working with data in Kotlin. Kotlin's standard library comes with comprehensive file manipulation capabilities, thanks to the java.io.File functionality that it builds upon. In this article, we'll demonstrate how to read text from files using the File class and explore different methods to suit your needs.
1. Reading a File Line by Line
When you want to read a file line by line, the readLines() function is an ideal choice. It reads all lines from a file and returns them as a list of strings.
import java.io.File
fun main() {
val fileName = "example.txt"
val lines: List<String> = File(fileName).readLines()
lines.forEach { line ->
println(line)
}
}In this snippet, we open example.txt, read all its lines at once, and print them out. The readLines() function is simple and effective for smaller files.
2. Reading a File into a Single String
If you're dealing with file contents where lines don't matter but the entire text does, consider using readText() to read the file into a single string:
import java.io.File
fun main() {
val fileName = "example.txt"
val content: String = File(fileName).readText()
println(content)
}This method is optimal when you need to treat the file as a whole, such as processing data or searching for occurrences within the text.
3. Reading Large Files with a Buffer
Handling large files efficiently might require reading files with buffered streams. Kotlin offers bufferedReader() for this purpose:
import java.io.File
fun main() {
val fileName = "example.txt"
File(fileName).bufferedReader().use { reader ->
reader.forEachLine { line ->
println(line)
}
}
}Using bufferedReader() here allows you to handle large files by reading the contents into memory in chunks, rather than all at once. This method is efficient for applications working with big data or streams.
Conclusion
Kotlin makes reading text files straightforward with its clear and concise APIs. Whether you handle small or large files, these methods provide a toolkit for safe and efficient file operations. Depending on your requirements, choose the appropriate method to ensure your code remains scalable and performant.