Scala Files.copy
Copy a file to an independent destination before editing it.
A simple example
Files.copy
- Start with Source file containing A
- Do this Copy to a second file
- Result Both contain A
Syntax
Files.copy(original, copy)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonKeep 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.
import java.nio.file.Files
import java.nio.file.Path
object Lesson {
def main(args: Array[String]): Unit = {
val base = Files.createTempDirectory("lesson-")
try {
val original = Files.writeString(base.resolve("original"), "paid")
val copy = Files.copy(original, base.resolve("copy"))
Files.writeString(copy, "collected")
println(Files.readString(original))
} finally {
val tree = Files.walk(base)
try tree.sorted(java.util.Comparator.reverseOrder[Path]()).forEach(p => Files.delete(p))
finally tree.close()
}
}
}
paid
The original still contains only the payment status after the destination changes.
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?
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?
What to watch for
Existing-destination and overwrite rules vary between APIs. This exercise uses a fresh destination.