Kotlin File Reading
Kotlin provides clean, concise APIs for reading files. These APIs build on top of Java's file system but remove the boilerplate. You can read files line by line, all at once, or as a stream — and Kotlin handles resource cleanup automatically.
Reading an Entire File as Text
import java.io.File
fun main() {
val file = File("data.txt")
// Read the entire file as one String
val content = file.readText()
println(content)
}Reading All Lines as a List
import java.io.File
fun main() {
val lines = File("names.txt").readLines()
println("Total lines: ${lines.size}")
lines.forEachIndexed { i, line ->
println("$i: $line")
}
}Reading Line by Line (Memory Efficient)
import java.io.File
fun main() {
File("large_log.txt").forEachLine { line ->
if (line.contains("ERROR")) {
println("Found: $line")
}
}
// File is closed automatically after the block
}This approach reads one line at a time and does not load the entire file into memory — ideal for large files.
Reading with useLines
import java.io.File
fun main() {
val errorCount = File("app.log").useLines { lines ->
lines.filter { it.startsWith("[ERROR]") }.count()
}
println("Error count: $errorCount")
// File is closed automatically when useLines block ends
}Reading Bytes
import java.io.File
fun main() {
val bytes = File("image.png").readBytes()
println("File size: ${bytes.size} bytes")
}Checking If a File Exists
import java.io.File
fun main() {
val file = File("config.txt")
if (file.exists()) {
println("File found: ${file.name}")
println("Size: ${file.length()} bytes")
println("Path: ${file.absolutePath}")
} else {
println("File not found")
}
}File Reading Workflow Diagram
File("path/to/file.txt")
│
├── .readText() → entire file as String (small files)
├── .readLines() → all lines as List (small files)
├── .forEachLine { } → one line at a time (large files)
├── .useLines { seq } → sequence of lines (large files, auto-close)
└── .readBytes() → raw bytes (binary files)
Handling File Not Found
import java.io.File
fun readSafely(path: String): String? {
val file = File(path)
return if (file.exists() && file.isFile) {
file.readText()
} else {
println("File not found: $path")
null
}
}
fun main() {
val content = readSafely("config.txt") ?: "Using defaults"
println(content)
}Reading a CSV File
import java.io.File
data class Employee(val id: Int, val name: String, val department: String, val salary: Double)
fun readEmployees(path: String): List {
return File(path).readLines()
.drop(1) // skip header row
.map { line ->
val parts = line.split(",")
Employee(
id = parts[0].trim().toInt(),
name = parts[1].trim(),
department = parts[2].trim(),
salary = parts[3].trim().toDouble()
)
}
}
fun main() {
// Sample CSV content:
// id,name,department,salary
// 1,Alice,Tech,95000.0
// 2,Bob,Sales,62000.0
// val employees = readEmployees("employees.csv")
// employees.forEach { println(it) }
println("CSV parser ready to read employee data")
} Practical Example: Log Analyzer
import java.io.File
fun analyzeLog(path: String) {
if (!File(path).exists()) {
println("Log file not found: $path")
return
}
var totalLines = 0
val errorLines = mutableListOf()
val warnLines = mutableListOf()
File(path).forEachLine { line ->
totalLines++
when {
line.contains("[ERROR]") -> errorLines.add(line)
line.contains("[WARN]") -> warnLines.add(line)
}
}
println("Total lines : $totalLines")
println("Error count : ${errorLines.size}")
println("Warning count: ${warnLines.size}")
if (errorLines.isNotEmpty()) {
println("\nFirst error: ${errorLines.first()}")
}
}
fun main() {
analyzeLog("application.log")
} 