How to Read File Line by Line in Kotlin Easily
In Kotlin, you can read a file line by line using
File(path).forEachLine {} or File(path).readLines(). These methods let you process each line one at a time or get all lines as a list.Syntax
Here are two common ways to read a file line by line in Kotlin:
File(path).forEachLine { line -> }: Processes each line one by one inside the lambda.File(path).readLines(): Reads all lines into a list of strings.
You need to import java.io.File to use these.
kotlin
import java.io.File // Using forEachLine File("filename.txt").forEachLine { line -> println(line) } // Using readLines val lines = File("filename.txt").readLines() for (line in lines) { println(line) }
Example
This example shows how to read a file named example.txt line by line and print each line to the console.
kotlin
import java.io.File fun main() { val fileName = "example.txt" File(fileName).forEachLine { line -> println(line) } }
Output
Hello, world!
This is line 2.
This is line 3.
Common Pitfalls
Common mistakes when reading files line by line in Kotlin include:
- Not importing
java.io.File. - Using a wrong file path or missing the file, causing exceptions.
- Reading large files with
readLines()which loads all lines into memory at once, possibly causing memory issues. - Not handling exceptions like
FileNotFoundException.
Always ensure the file exists and handle exceptions if needed.
kotlin
import java.io.File import java.io.FileNotFoundException fun main() { val fileName = "missing.txt" try { File(fileName).forEachLine { line -> println(line) } } catch (e: FileNotFoundException) { println("File not found: $fileName") } }
Output
File not found: missing.txt
Quick Reference
Summary tips for reading files line by line in Kotlin:
- Use
forEachLinefor memory-efficient line processing. - Use
readLinesif you need all lines at once. - Always import
java.io.File. - Handle exceptions for missing or unreadable files.
Key Takeaways
Use File(path).forEachLine { } to read and process each line efficiently.
readLines() returns all lines as a list but uses more memory.
Always import java.io.File to work with files in Kotlin.
Handle exceptions to avoid crashes when files are missing.
Check your file path carefully to ensure the file can be found.