Library contents

Kotlin Files.readString

Open a small text note and read back its contents.

A simple example

Files.readString

  1. Start with A file containing A
  2. Do this Read it as text
  3. Result "A"
Decoding the single ASCII byte yields the letter A.

Syntax

Kotlin syntax
Files.readString(path)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Read a saved shopping note

A small application saves a human-readable note for the next time it opens. Choose the text encoding and read or write the file deliberately so the saved characters can be recovered as intended.

Resultmilk
Lesson.kt
import java.nio.file.Files

fun main() {
    val path = Files.createTempFile("receipt", ".txt")
    try {
        Files.writeString(path, "milk")
        println(Files.readString(path))
    } finally {
        Files.deleteIfExists(path)
    }
}
Output
milk

The program saves milk, then reads the same four characters from its temporary file.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?

GivenFile contents “clay”
Worked resultclay

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

Use an explicit text encoding for shared data. A large file is usually better read in smaller pieces.

Documentation for Files.readString