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

后端 未结 19 1489
旧巷少年郎
旧巷少年郎 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条回答
  •  萌比男神i
    2020-11-28 04:16

    I like yura's stream solution, but it (and the others) recurses into hidden directories. We can also simplify by making use of the fact that listFiles returns null for a non-directory.

    def tree(root: File, skipHidden: Boolean = false): Stream[File] = 
      if (!root.exists || (skipHidden && root.isHidden)) Stream.empty 
      else root #:: (
        root.listFiles match {
          case null => Stream.empty
          case files => files.toStream.flatMap(tree(_, skipHidden))
      })
    

    Now we can list files

    tree(new File(".")).filter(f => f.isFile && f.getName.endsWith(".html")).foreach(println)
    

    or realise the whole stream for later processing

    tree(new File("dir"), true).toArray
    

提交回复
热议问题