Scala Using.resource with Files.list
Enumerate immediate directory entries and filter their names by suffix.
A simple example
Using.resource with Files.list
- Start with One folder containing a.txt and b.txt
- Do this List and sort its names
- Result a.txt, b.txt
Syntax
Using.resource(Files.list(base))(consume)
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 LessonCount 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.
import java.nio.file.Files
import java.nio.file.Path
import scala.util.Using
object Lesson {
def main(args: Array[String]): Unit = {
val base = Files.createTempDirectory("lesson-")
try {
List("a.csv", "b.csv", "notes.txt").foreach(name => Files.createFile(base.resolve(name)))
val invoices = Using.resource(Files.list(base)) { paths =>
paths.filter(p => Files.isRegularFile(p) && p.toString.endsWith(".csv")).count()
}
println(invoices)
} finally {
val tree = Files.walk(base)
try tree.sorted(java.util.Comparator.reverseOrder[Path]()).forEach(p => Files.delete(p))
finally tree.close()
}
}
}
2
The two CSV names pass the filter and the text note is excluded.
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.
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.
What to watch for
Directory enumeration order is unspecified. Sort first if the order matters.