Library contents

Scala FileAlreadyExistsException

An exclusive creation on the local filesystem rejects a name already used by another shift.

A simple example

FileAlreadyExistsException

  1. Start with A file named a.txt already exists
  2. Do this Try exclusive creation at the same name
  3. Result Creation fails
Exclusive creation protects the existing file from replacement.

Syntax

Scala syntax
Files.createFile(report)
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 Lesson

Save a report without replacing the first copy

Two shifts try to save their report under the same filename. The second shift needs to learn that the name is taken while the first shift's report stays available.

ResultChoose a new report name
Lesson.scala
import java.nio.file.Files
import java.nio.file.FileAlreadyExistsException

object Lesson {
    def main(args: Array[String]): Unit = {
        val report = Files.createTempFile("shift-", ".txt")
        try {
            Files.createFile(report)
        } catch {
            case problem: FileAlreadyExistsException =>
                println("Choose a new report name")
        } finally {
            Files.deleteIfExists(report)
        }
    }
}
Output
Choose a new report name

The exclusive create sees the existing report. Its earlier contents are preserved.

Advertisements

Issue the first parcel claim

The counter opens a new workspace for today’s pickup. Create the claim file exclusively so that an existing claim stays intact.

GivenUnused name
Worked resultClaim created

Preserve a previous reservation

The second counter tries a name already reserved by the first counter. Create the claim file exclusively so that an existing claim stays intact.

GivenExisting claim
Worked resultKeep earlier claim

What to watch for

The specific exception depends on the provider. The example creates and cleans up its own temporary report.

Documentation for FileAlreadyExistsException