首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >spark遍历hdfs目录下所有文件

spark遍历hdfs目录下所有文件

作者头像
静谧星空TEL
发布于 2021-04-27 12:26:59
发布于 2021-04-27 12:26:59
3.9K0
举报

1、查看hdfs   /home/data/test  目录下的所有文件

2、使用 org.apache.hadoop.fs.FileSystem 类遍历hdfs文件

代码语言:javascript
复制
package com.xtd.hdfs

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, FileUtil, Path}
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object HDFSUtils {

  def main(args: Array[String]): Unit = {
    val files = getHDFSFiles("hdfs://ns1/home/data/test")
    files.foreach(println(_))
  }

  /**
   * 给定hdfs目录返回目录下文件名的集合
   * @param hdfsDirectory
   * @return Array[String]
   */
  def getHDFSFiles(hdfsDirectory:String): Array[String] ={
    val configuration:Configuration = new Configuration()
//    configuration.set("fs.defaultFS", hdfsFileName)
    val fileSystem:FileSystem = FileSystem.get(configuration)
    val fsPath: Path = new Path(hdfsDirectory)
    val iterator = fileSystem.listFiles(fsPath, true)
    val list = new ListBuffer[String]
    while (iterator.hasNext) {
      val pathStatus = iterator.next()
      val hdfsPath = pathStatus.getPath
      val fileName = hdfsPath.getName
      list += fileName // list.append(fileName)
    }
    fileSystem.close()
    list.toArray
  }

}

 3、运行效果

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/06/30 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档