Skip to main content

πŸ“ File I/O

πŸ“– What is File I/O?​

File I/O (Input/Output) is the process of reading and writing files. It's essential for data storage, configuration management, logging, and more!

πŸ’‘ Reading Files​

Reading Entire File​

import java.io.File

fun main() {
// Read entire file as string
val content = File("data.txt").readText()
println(content)

// Read file as list of lines
val lines = File("data.txt").readLines()
for (line in lines) {
println(line)
}
}

Safe Reading​

import java.io.File

fun readFileSafe(filename: String): String? {
return try {
File(filename).readText()
} catch (e: Exception) {
println("Failed to read file: ${e.message}")
null
}
}

fun main() {
val content = readFileSafe("data.txt")
if (content != null) {
println("Content: $content")
} else {
println("Unable to read file")
}
}

Line-by-Line Processing​

import java.io.File

fun main() {
// Memory efficient (good for large files)
File("data.txt").forEachLine { line ->
println(line)
}

// useLines - automatically closes
val lineCount = File("data.txt").useLines { lines ->
lines.count()
}
println("Total lines: $lineCount")
}

✏️ Writing Files​

Overwriting​

import java.io.File

fun main() {
// Write text
File("output.txt").writeText("Hello\nKotlin!")

// Write line by line
val lines = listOf("First line", "Second line", "Third line")
File("output.txt").writeText(lines.joinToString("\n"))
}

Appending​

import java.io.File

fun main() {
val file = File("log.txt")

// Append text
file.appendText("Log 1\n")
file.appendText("Log 2\n")
file.appendText("Log 3\n")
}

Safe Writing​

import java.io.File

fun writeFileSafe(filename: String, content: String): Boolean {
return try {
File(filename).writeText(content)
true
} catch (e: Exception) {
println("Failed to write file: ${e.message}")
false
}
}

fun main() {
if (writeFileSafe("data.txt", "Hello Kotlin!")) {
println("File saved successfully")
}
}

🎯 Practical Examples​

Simple Notebook​

import java.io.File

class SimpleNotebook(private val filename: String) {
private val file = File(filename)

fun write(content: String) {
file.writeText(content)
println("Saved successfully")
}

fun append(content: String) {
file.appendText("$content\n")
println("Appended successfully")
}

fun read(): String {
return if (file.exists()) {
file.readText()
} else {
"File not found"
}
}

fun clear() {
file.writeText("")
println("Content cleared")
}
}

fun main() {
val notebook = SimpleNotebook("mynotes.txt")

notebook.write("First note")
notebook.append("Second note")
notebook.append("Third note")

println("\n=== Notebook Content ===")
println(notebook.read())
}

Logger​

import java.io.File
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class Logger(private val filename: String) {
private val file = File(filename)
private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

fun log(message: String) {
val timestamp = LocalDateTime.now().format(formatter)
file.appendText("[$timestamp] $message\n")
}

fun info(message: String) = log("INFO: $message")
fun error(message: String) = log("ERROR: $message")
fun warn(message: String) = log("WARN: $message")

fun readLogs(): String {
return if (file.exists()) {
file.readText()
} else {
"No logs"
}
}
}

fun main() {
val logger = Logger("app.log")

logger.info("App started")
logger.warn("Low memory")
logger.error("Connection failed")

println(logger.readLogs())
}

CSV File Processing​

import java.io.File

data class Person(val name: String, val age: Int, val city: String)

object CsvHandler {
fun writeCsv(filename: String, people: List<Person>) {
val csv = StringBuilder()
csv.append("Name,Age,City\n")

for (person in people) {
csv.append("${person.name},${person.age},${person.city}\n")
}

File(filename).writeText(csv.toString())
}

fun readCsv(filename: String): List<Person> {
val file = File(filename)
if (!file.exists()) return emptyList()

val lines = file.readLines()
if (lines.isEmpty()) return emptyList()

return lines.drop(1).map { line ->
val parts = line.split(",")
Person(parts[0], parts[1].toInt(), parts[2])
}
}
}

fun main() {
val people = listOf(
Person("John Doe", 25, "Seoul"),
Person("Jane Smith", 30, "Busan"),
Person("Bob Lee", 28, "Daegu")
)

// Save CSV
CsvHandler.writeCsv("people.csv", people)
println("CSV saved successfully")

// Read CSV
val loaded = CsvHandler.readCsv("people.csv")
println("\n=== CSV Content ===")
loaded.forEach { println(it) }
}

Configuration File Management​

import java.io.File

class Config(private val filename: String) {
private val settings = mutableMapOf<String, String>()

init {
load()
}

private fun load() {
val file = File(filename)
if (file.exists()) {
file.forEachLine { line ->
val parts = line.split("=")
if (parts.size == 2) {
settings[parts[0].trim()] = parts[1].trim()
}
}
}
}

fun save() {
val content = settings.entries.joinToString("\n") {
"${it.key}=${it.value}"
}
File(filename).writeText(content)
}

fun set(key: String, value: String) {
settings[key] = value
}

fun get(key: String): String? {
return settings[key]
}

fun getAll(): Map<String, String> {
return settings.toMap()
}
}

fun main() {
val config = Config("app.config")

// Save settings
config.set("host", "localhost")
config.set("port", "8080")
config.set("timeout", "3000")
config.save()

// Read settings
println("Host: ${config.get("host")}")
println("Port: ${config.get("port")}")

println("\n=== All Settings ===")
config.getAll().forEach { (key, value) ->
println("$key = $value")
}
}

πŸ“‚ File/Directory Management​

File Information​

import java.io.File

fun main() {
val file = File("data.txt")

println("Exists: ${file.exists()}")
println("Is file: ${file.isFile}")
println("Is directory: ${file.isDirectory}")
println("Size: ${file.length()} bytes")
println("Absolute path: ${file.absolutePath}")
println("Name: ${file.name}")
println("Parent folder: ${file.parent}")
}

Directory Operations​

import java.io.File

fun main() {
// Create directory
val dir = File("mydata")
dir.mkdir()

// List files
dir.listFiles()?.forEach { file ->
println("${file.name} (${if (file.isDirectory) "folder" else "file"})")
}

// Find all files recursively
dir.walk().forEach { file ->
println(file.absolutePath)
}
}

File Copy/Delete​

import java.io.File

fun main() {
val source = File("source.txt")
val dest = File("dest.txt")

// Copy
source.copyTo(dest, overwrite = true)

// Move
source.renameTo(File("moved.txt"))

// Delete
dest.delete()

// Delete entire directory
File("mydata").deleteRecursively()
}

πŸ€” FAQ​

Q1. What if the file doesn't exist?​

A: Exception handling is required!

fun readFileSafe(filename: String): String {
val file = File(filename)

if (!file.exists()) {
return "File not found"
}

return try {
file.readText()
} catch (e: Exception) {
"Read failed: ${e.message}"
}
}

Q2. What about large files?​

A: Process line by line!

// ❌ Risk of out of memory
val content = File("huge.txt").readText()

// βœ… Line-by-line processing
File("huge.txt").forEachLine { line ->
processLine(line)
}

Q3. What about path separators?​

A: Use File.separator!

// ❌ Different on each OS
val path = "data/files/text.txt"

// βœ… Works on all OS
val file = File("data", "files").resolve("text.txt")
// Or
val path2 = listOf("data", "files", "text.txt").joinToString(File.separator)

🎬 Conclusion​

Store and manage data with file I/O!

Key Takeaways:
βœ… Read files with readText()
βœ… Write files with writeText()
βœ… Process line-by-line with forEachLine()
βœ… Check file existence with exists()
βœ… Exception handling is essential

Next Step: Learn about pattern matching in Regular Expressions!