Library contents

Kotlin Path.listDirectoryEntries

Enumerate immediate directory entries and filter their names by suffix.

A simple example

Path.listDirectoryEntries

  1. Start with One folder containing a.txt and b.txt
  2. Do this List and sort its names
  3. Result a.txt, b.txt
Listing discovers the entries. Sorting makes their displayed order predictable.

Syntax

Kotlin syntax
base.listDirectoryEntries("*.csv")
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

Count only the invoices in a folder

A market stall saves two CSV invoices and a text note in the same folder. Count just the CSV entries for the daily summary without depending on the order returned by the filesystem.

Result2
Lesson.kt
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.isRegularFile

fun main() {
    val base = Files.createTempDirectory("lesson-")
    try {
        for (name in listOf("a.csv", "b.csv", "notes.txt")) Files.createFile(base.resolve(name))
        println(base.listDirectoryEntries("*.csv").count { it.isRegularFile() })
    } finally {
        base.toFile().deleteRecursively()
    }
}
Output
2

The two CSV names pass the filter and the text note is excluded.

Advertisements

Inventory class submissions

A teacher receives two top-level files and one file in a team folder. Count regular files in the top-level folder only. Do not count subfolders as files.

Givenanna.pdf · li.pdf · team/plan.pdf
Worked result2

Inventory rehearsal parts

A school stores one score and two parts in a subfolder. Count regular files in the top-level folder only. Do not count subfolders as files.

Givenscore.pdf · parts/alto.pdf · parts/bass.pdf
Worked result1

What to watch for

Directory enumeration order is unspecified. Sort first if the order matters.

Documentation for Path.listDirectoryEntries