skip to content

How do you read an entire file into a String and write a String to a file in Kotlin using the standard library? Name the relevant File extension functions.

level: juniorimportance: must knowfreq 75%

answer

  1. readText = whole file as String
  2. writeText truncates, appendText adds
  3. readLines = List<String>
  4. Default charset is UTF-8
  5. Eager: loads whole file into memory

basics

~10 s

Use File("path").readText() to get the whole file as one String, and File("path").writeText("content") to replace the file's contents. Both are Kotlin extension functions that open and close the file for you.

solid answer

~40 s

Kotlin's stdlib adds extension functions to java.io.File. `File.readText(charset = Charsets.UTF_8): String` reads the whole file into one String; `File.writeText(text, charset)` truncates the file and writes the String; `File.appendText(text)` adds to the end. `readLines(): List<String>` returns every line as a list. All of them open the underlying stream, do the work, and close it automatically, so you don't manage a Reader/Writer yourself. They default to UTF-8 but accept a Charset. They're convenient for small-to-medium files because the entire content is materialized in memory — for large files you'd stream with `bufferedReader().use { }`, `forEachLine`, or `useLines` instead. These functions throw IOException on failure (e.g. file missing, no permission).

code

kotlin · 9 lines
kotlin
import java.io.File

fun main() {
    val file = File("greeting.txt")
    file.writeText("Hello\n")
    file.appendText("World\n")
    println(file.readText())          // Hello\nWorld\n
    println(file.readLines())         // [Hello, World]
}

go deeper

for a junior

Knows readText/writeText exist and that writeText overwrites.

for a middle

Mentions UTF-8 default, appendText vs writeText, and that content is loaded into memory.

for a senior

Explains the eager-memory trade-off and points to streaming alternatives for large files; notes IOException handling.

for a principal

Frames these as convenience extensions over java.io and discusses charset correctness and memory/throughput limits at scale.

## What these are Kotlin doesn't ship its own file type — it reuses `java.io.File` and decorates it with **extension functions** in `kotlin.io`. An *extension function* lets you call `file.readText()` as if `readText` were a method on `File`, even though it isn't part of the Java class. ## Reading whole content - `File.readText(charset: Charset = Charsets.UTF_8): String` — reads the **entire** file into a single `String`. A *Charset* is the encoding (how bytes map to characters); the default is UTF-8. - `File.readLines(charset = Charsets.UTF_8): List<String>` — reads the file and returns each line as an element in a `List<String>`. Line breaks are stripped. - `File.readBytes(): ByteArray` — the raw bytes, for binary data. ## Writing whole content - `File.writeText(text: String, charset = Charsets.UTF_8)` — **truncates** (empties) the file, then writes the String. If the file doesn't exist it's created. - `File.appendText(text: String, charset = Charsets.UTF_8)` — keeps existing content and adds `text` to the end. - `File.writeBytes(array: ByteArray)` — write raw bytes. ```kotlin import java.io.File val f = File("notes.txt") f.writeText("line 1\n") // creates/overwrites f.appendText("line 2\n") // adds to end val whole: String = f.readText() // "line 1\nline 2\n" val lines: List<String> = f.readLines() // ["line 1", "line 2"] ``` ## Key properties - **They manage the stream for you.** Internally each one opens a `Reader`/`Writer`, performs the I/O, and closes it in a `finally` block — you never call `.close()`. - **They are eager and load everything into memory.** `readText`/`readLines` materialize the full file. That's fine for config files but dangerous for multi-gigabyte logs (risk of `OutOfMemoryError`). For those, stream with `bufferedReader().use`, `forEachLine`, or `useLines`. - **They can throw.** All do I/O, so they can throw `java.io.IOException` (subclasses like `FileNotFoundException`) — a checked-in-Java exception that Kotlin treats as unchecked but you should still handle. ## When to use what | Need | Use | |------|-----| | Small file, want one String | `readText()` | | Small file, want lines | `readLines()` | | Overwrite file | `writeText()` | | Append | `appendText()` | | Huge file | streaming (`useLines`, `forEachLine`) |

  • What charset do readText and writeText use by default?
    UTF-8 (Charsets.UTF_8). You can pass a different Charset as an argument.
  • Does writeText append or overwrite?
    It overwrites (truncates the file first). Use appendText to add to existing content.

readText is like photocopying a whole document at once; for a giant book you'd read page by page (streaming) instead.

saying these in an interview costs you the question

  • Thinking readText/writeText are methods on java.io.File rather than Kotlin extensions
  • Believing writeText appends instead of truncating
  • Claiming these handle arbitrarily large files safely
  • Saying you must manually close a stream after readText
  • Assuming the default charset is platform-default rather than UTF-8

context