CodeBlanks Logo Icon CodeBlanks

readText

Learn to read files with File.readText.

readText: Read the whole file

readText() returns the entire content of a file as a single String. Line breaks remain as \n characters inside the string. The default encoding is UTF-8; you can specify it with readText(Charsets.UTF_8).

val f = File("not.txt")
f.writeText("one\ntwo")
val content = f.readText()
println(content)

The output is a two-line text. readText suits small and medium files; it loads the whole content into memory. For very large files prefer readLines or useLines for line-by-line reading.

Encoding

Files are stored as byte arrays; text is converted to bytes through an encoding. In Kotlin the default encoding is UTF-8, which supports all Unicode characters including Turkish letters. Files from legacy systems may use ISO-8859-9 (for Turkish) or windows-1254.

val content = f.readText(Charsets.UTF_8)

If you use the wrong encoding, Turkish letters look broken (for example "ö" instead of "ö"). So it is a good habit to specify the encoding explicitly. Calling readText() with no argument assumes UTF-8.

Practice Write to a file and read with readText

Create val f = File("not.txt"). Write with f.writeText("Hello Kotlin"). Read and print with println(f.readText()). Add the import java.io.File import.

Starter code

Main.kt
import java.io.File

// File object for path not.txt
// write "Hello Kotlin" to it
// read with readText and println
fun main() {
    // write here
}

Sample solution

Main.kt
fun main() {
    val f = File("not.txt")
    f.writeText("Hello Kotlin")
    println(f.readText())
}

Expected output

Hello Kotlin

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Read the file

Question
val content = f.____()
Answer
val content = f.readText()

Explanation: readText reads all content as a single string.

2 Match the readText concepts

Term Meaning
readText() Reads all content
String Return type
UTF-8 Default encoding
\n Line break

3 What type does readText() return?

  • List<String>
  • String Correct answer
  • ByteArray
  • Int

Explanation: readText returns all content as a single String.

All lessons in Intermediate