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

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

    Here's a similar solution to Rex Kerr's, but incorporating a file filter:

    import java.io.File
    def findFiles(fileFilter: (File) => Boolean = (f) => true)(f: File): List[File] = {
      val ss = f.list()
      val list = if (ss == null) {
        Nil
      } else {
        ss.toList.sorted
      }
      val visible = list.filter(_.charAt(0) != '.')
      val these = visible.map(new File(f, _))
      these.filter(fileFilter) ++ these.filter(_.isDirectory).flatMap(findFiles(fileFilter))
    }
    

    The method returns a List[File], which is slightly more convenient than Array[File]. It also ignores all directories that are hidden (ie. beginning with '.').

    It's partially applied using a file filter of your choosing, for example:

    val srcDir = new File( ... )
    val htmlFiles = findFiles( _.getName endsWith ".html" )( srcDir )
    

提交回复
热议问题