Kotlin reuses Java I/O on the JVM: java.io.File, NIO paths, and extension helpers like readText() and writeText() on File. For large files prefer streams or NIO channels.
Reading and writing
val text = File("data.txt").readText()
File("out.txt").writeText(text.uppercase())
Use use blocks for streams—Kotlin's version of try-with-resources. On Native targets, expect platform-specific APIs.
Important interview questions and answers
- Q: readText risks?
A: Loads entire file into memory—avoid for huge logs; use line sequences or buffered readers. - Q: use function?
A: Closes Closeable resources automatically after the lambda—prevents descriptor leaks.
Self-check
- Which method reads a small text file in one call?
- How does Kotlin close streams safely?
Tip: Prefer use on streams—like try-with-resources in Java.
Interview prep
- readText?
File(path).readText() for small files; useLines for streaming.
- use function?
Closes Closeable after block—like try-with-resources.