How do I list all files in a subdirectory in scala?

后端 未结 19 1477
旧巷少年郎
旧巷少年郎 2020-11-28 03:35

Is there a good \"scala-esque\" (I guess I mean functional) way of recursively listing files in a directory? What about matching a particular pattern?

For example re

19条回答
  •  感情败类
    2020-11-28 04:04

    You can use tail recursion for it:

    object DirectoryTraversal {
      import java.io._
    
      def main(args: Array[String]) {
        val dir = new File("C:/Windows")
        val files = scan(dir)
    
        val out = new PrintWriter(new File("out.txt"))
    
        files foreach { file =>
          out.println(file)
        }
    
        out.flush()
        out.close()
      }
    
      def scan(file: File): List[File] = {
    
        @scala.annotation.tailrec
        def sc(acc: List[File], files: List[File]): List[File] = {
          files match {
            case Nil => acc
            case x :: xs => {
              x.isDirectory match {
                case false => sc(x :: acc, xs)
                case true => sc(acc, xs ::: x.listFiles.toList)
              }
            }
          }
        }
    
        sc(List(), List(file))
      }
    }
    

提交回复
热议问题