Scala Using.resource with Files.walk
Walk a directory tree and select matching regular files.
A simple example
Using.resource with Files.walk
- Start with Folder a contains b/c.txt
- Do this Visit descendants
- Result The walk reaches c.txt
Syntax
Using.resource(Files.walk(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 LessonFind a receipt below the month folder
A treasurer has one receipt in a month folder and a note beside that folder. A recursive inventory should locate the nested CSV receipt while leaving the unrelated note out of its total.
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 {
val month = Files.createDirectory(base.resolve("March"))
Files.createFile(month.resolve("dues.csv"))
Files.createFile(base.resolve("notes.txt"))
val count = Using.resource(Files.walk(base)) { paths =>
paths.filter(p => Files.isRegularFile(p) && p.toString.endsWith(".csv")).count()
}
println(count)
} finally {
val tree = Files.walk(base)
try tree.sorted(java.util.Comparator.reverseOrder[Path]()).forEach(p => Files.delete(p))
finally tree.close()
}
}
}
1
The month folder contributes one matching receipt below the top level.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files throughout the folder tree, including its subfolders.
What to watch for
Following symbolic links during recursion can revisit directories. Choose link handling deliberately.