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

后端 未结 19 1478
旧巷少年郎
旧巷少年郎 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 03:57

    Why are you using Java's File instead of Scala's AbstractFile?

    With Scala's AbstractFile, the iterator support allows writing a more concise version of James Moore's solution:

    import scala.reflect.io.AbstractFile  
    def tree(root: AbstractFile, descendCheck: AbstractFile => Boolean = {_=>true}): Stream[AbstractFile] =
      if (root == null || !root.exists) Stream.empty
      else
        (root.exists, root.isDirectory && descendCheck(root)) match {
          case (false, _) => Stream.empty
          case (true, true) => root #:: root.iterator.flatMap { tree(_, descendCheck) }.toStream
          case (true, false) => Stream(root)
        }
    

提交回复
热议问题