我有一个程序可以从嵌套目录中获取数据然后处理它们。我认为这些目录具有均匀的结构,只需执行以下操作即可检索它们:
val inputPath = basePath + dataSet + "/*/*/*/*/*/"
但是,某些目录甚至更加嵌套。例如,假设我们有这样的目录结构:
/hello/world/my/name/is/somedatafiles
可能还有另一个如下所示的目录结构:/hello/world/my/name/is/waldo/somedatafiles
有没有办法在 Scala 中以不均匀的目录结构到达目录末尾?
最佳答案
看看来自 Rosettacode.org 的这个片段:
import java.io.File
object `package` {
def walkTree(file: File): Iterable[File] = {
val children = new Iterable[File] {
def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty
}
Seq(file) ++: children.flatMap(walkTree(_))
}
}
object Test extends App {
val dir = new File("/home/user")
for(f <- walkTree(dir)) println(f)
for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f)
}
https://rosettacode.org/wiki/Walk_a_directory/Recursively#Scala
这应该可以解决问题。
关于java - 检查文件是否存在于嵌套的不均匀目录中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52302759/