Task

Walk a given directory tree and print files matching a given pattern.


Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory.


Note: Please be careful when running any code examples found here.



Related task

   Walk a directory/Non-recursively   (read a single directory). 


import java.io.File
 
object `package` { 
  def walkTree(file: File): Iterable[File] = {
    val children = new Iterable[File] {
      def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty
    }
    Seq(file) ++: children.flatMap(walkTree(_))
  }
}
 
object Test extends App {
  val dir = new File("/home/user")
  for(f <- walkTree(dir)) println(f)
  for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f)
}