Kotlin Path.deleteExisting
Remove an existing file and check that its name is gone.
A simple example
Path.deleteExisting
- Start with A practice file exists
- Do this Delete that file
- Result The path is absent
Syntax
preview.deleteExisting()
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.jarClear a disposable print preview
A library kiosk creates a preview whenever a borrower asks for a printout. After printing, the kiosk must remove that scratch file and confirm that the job has finished cleaning up.
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.deleteExisting
fun main() {
val base = Files.createTempDirectory("lesson-")
try {
val preview = Files.createFile(base.resolve("preview"))
preview.deleteExisting()
if (Files.notExists(preview)) println("removed")
} finally {
base.toFile().deleteRecursively()
}
}
removed
The check runs after removal and confirms the preview path is absent.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. The desk removes the temporary note after handover. Does its original name still identify an entry?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. The desk removes the temporary note after handover. Does its original name still identify an entry?
What to watch for
Deletion and missing-file behavior vary by API. Limit cleanup to paths created by this job.