How to Use BufferedReader in Kotlin: Simple Guide
In Kotlin, you can use
bufferedReader() to read text from an input stream efficiently by wrapping it in a buffered reader. This allows you to read lines or characters easily using methods like readLine().Syntax
The bufferedReader() function creates a buffered reader from an input source like a file or input stream. You can then use methods like readLine() to read text line by line.
Example parts:
inputStream.bufferedReader(): Wraps the input stream with a buffered reader.readLine(): Reads one line of text.use { }: Ensures the reader is closed automatically after use.
kotlin
val reader = inputStream.bufferedReader() val line = reader.readLine()
Example
This example reads lines from standard input until an empty line is entered, then prints each line.
kotlin
fun main() {
println("Enter text lines (empty line to stop):")
val lines = mutableListOf<String>()
System.`in`.bufferedReader().use { reader ->
while (true) {
val line = reader.readLine() ?: break
if (line.isEmpty()) break
lines.add(line)
}
}
println("You entered:")
lines.forEach { println(it) }
}Output
Enter text lines (empty line to stop):
Hello
World
You entered:
Hello
World
Common Pitfalls
Common mistakes when using bufferedReader() include:
- Not closing the reader, which can cause resource leaks. Use
use { }to close automatically. - Assuming
readLine()never returnsnull. It returnsnullat the end of input. - Reading input without checking for empty lines or end of stream, causing infinite loops.
kotlin
/* Wrong way: Not closing reader and ignoring null */ val reader = System.`in`.bufferedReader() while (true) { val line = reader.readLine() // no null check println(line) // may print null and cause issues } /* Right way: Using use and null check */ System.`in`.bufferedReader().use { reader -> while (true) { val line = reader.readLine() ?: break println(line) } }
Quick Reference
Summary tips for using bufferedReader() in Kotlin:
- Wrap input streams or files with
bufferedReader()for efficient reading. - Use
readLine()to read text line by line. - Always use
use { }to close the reader automatically. - Check for
nullfromreadLine()to detect end of input.
Key Takeaways
Use bufferedReader() to wrap input streams for efficient text reading.
Always close the buffered reader using use { } to avoid resource leaks.
Check for null from readLine() to handle end of input safely.
Read input line by line with readLine() for simple text processing.