如何列出Hdfs目录和子目录中文件的路径? [英] How to list the path of files inside Hdfs directory and subdirectory?

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

问题描述

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

Could not figure out a way to list all files in directory and subdirectories.

这是我正在使用的代码,该代码列出了特定目录中的文件,但是列出了内部是否有子部门的文件:

Here is the code that I'm using which lists files in a specific directory but files if there is a subdorectory inside:

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()) }

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

the above code lists all the files inside the directory but I need it to be recursive.

推荐答案

只要发现新文件夹,您都可以进行递归:

You could go for a recursion whenever you discover a new folder:

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
}

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

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