kotlinbeginner
File I/O — Read, Write, and Process
Read and write files in Kotlin: readText, useLines, buffered I/O, and file tree walking.
kotlinPress ⌘/Ctrl + Shift + C to copy
import java.io.File
import java.nio.file.*
import java.io.BufferedReader
fun main() {
val dir = File("temp-demo").also { it.mkdirs() }
// Write
val file = File(dir, "example.txt")
file.writeText("Hello, Kotlin!\nLine 2\nLine 3")
println("Written: ${file.absolutePath}")
// Append
file.appendText("\nLine 4 (appended)")
// Read entire file
val content = file.readText()
println("Content:\n$content")
// Read lines (into list)
val lines = file.readLines()
println("\nLines: ${lines.size}")
lines.forEachIndexed { i, line -> println(" ${i + 1}: $line") }
// useLines — lazy line-by-line (memory efficient)
println("\nFiltered lines:")
file.useLines { sequence ->
sequence
.filter { it.contains("Line") }
.map { it.uppercase() }
.forEach { println(" $it") }
}
// Buffered reader
file.bufferedReader().use { reader: BufferedReader ->
val first = reader.readLine()
println("\nFirst line: $first")
}
// Write structured data
data class Record(val name: String, val score: Int)
val records = listOf(
Record("Alice", 95),
Record("Bob", 82),
Record("Charlie", 91)
)
val csvFile = File(dir, "scores.csv")
csvFile.printWriter().use { out ->
out.println("name,score")
records.forEach { out.println("${it.name},${it.score}") }
}
println("\nCSV written: ${csvFile.readText()}")
// File properties
println("\nFile info:")
println(" Name: ${file.name}")
println(" Size: ${file.length()} bytes")
println(" Exists: ${file.exists()}")
println(" Is file: ${file.isFile}")
println(" Extension: ${file.extension}")
println(" Name without ext: ${file.nameWithoutExtension}")
// Walk directory tree
println("\nDirectory tree:")
dir.walkTopDown().forEach { f ->
val indent = " ".repeat(f.relativeTo(dir).path.count { it == File.separatorChar })
println("$indent${f.name}${if (f.isDirectory) "/" else ""}")
}
// Copy and move
val copy = File(dir, "example-copy.txt")
file.copyTo(copy, overwrite = true)
println("\nCopied to: ${copy.name}")
// NIO Path operations
val nioPath = Path.of(dir.path, "nio-test.txt")
Files.writeString(nioPath, "NIO content")
println("NIO read: ${Files.readString(nioPath)}")
// Cleanup
dir.deleteRecursively()
println("\nCleaned up demo directory")
}Use Cases
- Configuration file reading and writing
- CSV and log file processing
- Directory traversal and batch file operations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
kotlinbeginner
Extension Functions and Properties
Add methods to existing classes without inheritance: extension functions, properties, and generic extensions.
Best for: Adding utility methods to third-party types
#kotlin#extensions
kotlinbeginner
String Processing Utilities
Common string operations in Kotlin: split, join, pad, replace, regex, and template processing.
Best for: CSV and delimited data parsing
#kotlin#strings
kotlinbeginner
Kotlin String Manipulation Utilities
Essential string operations in Kotlin: templates, multiline, padding, splitting, regex, and buildString.
Best for: Text formatting and report generation
#kotlin#string
javabeginner
Read File Line by Line in Java
Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.
Best for: Processing log files line by line
#java#file-io