Scala 如何列出Hdfs目录和子目录中的文件路径?

Scala 如何列出Hdfs目录和子目录中的文件路径?,scala,hadoop,hdfs,Scala,Hadoop,Hdfs,无法找到列出目录和子目录中所有文件的方法 下面是我正在使用的代码,其中列出了特定目录中的文件,但如果其中有子目录,则列出了文件: val conf = new Configuration() val fs = FileSystem.get(new java.net.URI("hdfs://servername/"), conf) val status = fs.listStatus(new Path("path/to/folder/")) status.foreach { x => pri

无法找到列出目录和子目录中所有文件的方法

下面是我正在使用的代码,其中列出了特定目录中的文件,但如果其中有子目录,则列出了文件:

val conf = new Configuration()
val fs = FileSystem.get(new java.net.URI("hdfs://servername/"), conf)
val status = fs.listStatus(new Path("path/to/folder/"))
status.foreach { x => println(x.getPath.toString()) }

上面的代码列出了目录中的所有文件,但我需要它是递归的。

您可以在发现新文件夹时进行递归:

val hdfs = FileSystem.get(new Configuration())

def listFileNames(hdfsPath: String): List[String] = {

  hdfs
    .listStatus(new Path(hdfsPath))
    .flatMap { status =>
      // If it's a file:
      if (status.isFile)
        List(hdfsPath + "/" + status.getPath.getName)
      // If it's a dir and we're in a recursive option:
      else
        listFileNames(hdfsPath + "/" + status.getPath.getName)
    }
    .toList
    .sorted
}

排序在这里有什么用?您完全可以删除它,特别是在处理大量文件时。我通常喜欢在打印或单元测试时对列表进行排序。有没有办法过滤特定的文件扩展名?只说“.xml”您可以在生成的路径列表上应用筛选器:.filter_u.endsWith.xml,或者在status.getPath.getName.endsWith.xmlThank-cloud不知道如何筛选为2种或更多文件类型时直接在函数中应用,方法是返回Nil list?