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

后端 未结 19 1516
旧巷少年郎
旧巷少年郎 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:05

    And here's a mixture of the stream solution from @DuncanMcGregor with the filter from @Rick-777:

      def tree( root: File, descendCheck: File => Boolean = { _ => true } ): Stream[File] = {
        require(root != null)
        def directoryEntries(f: File) = for {
          direntries <- Option(f.list).toStream
          d <- direntries
        } yield new File(f, d)
        val shouldDescend = root.isDirectory && descendCheck(root)
        ( root.exists, shouldDescend ) match {
          case ( false, _) => Stream.Empty
          case ( true, true ) => root #:: ( directoryEntries(root) flatMap { tree( _, descendCheck ) } )
          case ( true, false) => Stream( root )
        }   
      }
    
      def treeIgnoringHiddenFilesAndDirectories( root: File ) = tree( root, { !_.isHidden } ) filter { !_.isHidden }
    

    This gives you a Stream[File] instead of a (potentially huge and very slow) List[File] while letting you decide which sorts of directories to recurse into with the descendCheck() function.

提交回复
热议问题