Library contents

Kotlin 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

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

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.kt
import java.nio.file.Files
import java.nio.file.FileAlreadyExistsException

fun main() {
    val report = Files.createTempFile("shift-", ".txt")
    try {
        Files.createFile(report)
    } catch (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