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

RDa*_*ata 2 hadoop scala 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 => println(x.getPath.toString()) }
Run Code Online (Sandbox Code Playgroud)

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

Xav*_*hot 5

每当您发现新文件夹时,您都可以进行递归:

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
}
Run Code Online (Sandbox Code Playgroud)