如何在scala中列出子目录中的所有文件? [英] How do I list all files in a subdirectory in scala?

查看:65
本文介绍了如何在scala中列出子目录中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种很好的scala-esque"(我想我的意思是功能性的)方法来递归列出目录中的文件?匹配特定模式怎么样?

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?

例如递归匹配c:\temp中的"a*.foo"的所有文件.

For example recursively all files matching "a*.foo" in c:\temp.

推荐答案

Scala 代码通常使用 Java 类来处理 I/O,包括读取目录.因此,您必须执行以下操作:

Scala code typically uses Java classes for dealing with I/O, including reading directories. So you have to do something like:

import java.io.File
def recursiveListFiles(f: File): Array[File] = {
  val these = f.listFiles
  these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles)
}

您可以收集所有文件,然后使用正则表达式进行过滤:

You could collect all the files and then filter using a regex:

myBigFileArray.filter(f => """.*\.html$""".r.findFirstIn(f.getName).isDefined)

或者您可以将正则表达式合并到递归搜索中:

Or you could incorporate the regex into the recursive search:

import scala.util.matching.Regex
def recursiveListFiles(f: File, r: Regex): Array[File] = {
  val these = f.listFiles
  val good = these.filter(f => r.findFirstIn(f.getName).isDefined)
  good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_,r))
}

这篇关于如何在scala中列出子目录中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆