Library contents

Kotlin Path.isRegularFile and isDirectory

Distinguish regular files from directories.

A simple example

Path.isRegularFile and isDirectory

  1. Start with A regular file a.txt
  2. Do this Test whether it is a directory
  3. Result No
A regular file and a directory have different entry types.

Syntax

Kotlin syntax
upload.isRegularFile()
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

Tell an uploaded file apart from its folder

A registration desk receives documents through an upload folder. The clerk needs to confirm that the submitted entry is a regular file and that the enclosing location is a directory before processing the batch.

Resultfile and folder
Lesson.kt
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.isRegularFile
import kotlin.io.path.isDirectory

fun main() {
    val base = Files.createTempDirectory("lesson-")
    try {
        val upload = Files.createFile(base.resolve("upload"))
        if (upload.isRegularFile() && base.isDirectory()) println("file and folder")
    } finally {
        base.toFile().deleteRecursively()
    }
}
Output
file and folder

The upload and its enclosing workspace have different entry types.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?

Givenspring / alto.txt
Worked resultRegular file

Locate a workshop handout

An instructor stores the current template in a class folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?

Givenceramics / glaze.pdf
Worked resultRegular file

What to watch for

Status checks describe the instant of inspection. Handle failure at the subsequent open.

Documentation for Path.isRegularFile and isDirectory