Library contents

Kotlin Path.copyTo

Copy a file to an independent destination before editing it.

A simple example

Path.copyTo

  1. Start with Source file containing A
  2. Do this Copy to a second file
  3. Result Both contain A
A copy keeps the original and creates another file with the same contents.

Syntax

Kotlin syntax
original.copyTo(copy)
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

Keep a separate copy of a receipt

A cashier gives a customer an annotated receipt and keeps the original for the daily ledger. Copy the saved receipt, add a note to the customer copy, and check what remains in the original.

Resultpaid
Lesson.kt
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.copyTo
import kotlin.io.path.readText
import kotlin.io.path.writeText

fun main() {
    val base = Files.createTempDirectory("lesson-")
    try {
        val original = base.resolve("original")
        val copy = base.resolve("copy")
        original.writeText("paid")
        original.copyTo(copy)
        copy.writeText("collected")
        println(original.readText())
    } finally {
        base.toFile().deleteRecursively()
    }
}
Output
paid

The original still contains only the payment status after the destination changes.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Make a second copy for the afternoon shift. Which text does the new file contain?

GivenFile contents “clay”
Worked resultclay

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Make a second copy for the afternoon shift. Which text does the new file contain?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

Existing-destination and overwrite rules vary between APIs. This exercise uses a fresh destination.

Documentation for Path.copyTo