1. 程式人生 > >列印(獲取)HDFS路徑下所有的檔名(包括子目錄下的)

列印(獲取)HDFS路徑下所有的檔名(包括子目錄下的)

前言

自己有個需求,如題,需要獲取HDFS路徑下所有的檔名,然後根據檔名用Spark進行後續操作。想了一下用Spark好像不太容易獲取到,還要遞迴的去獲取子目錄下的檔名,於是查了一下,最後用Hadoop的API搞定,這裡記錄下,方便以後會用到。

1、資料

測試路徑:/tmp/dkl,全路徑名hdfs://ambari.master.com:8020/tmp/dkl

用hadoop的命令檢視一下,該路徑下都有哪些檔案和資料夾

hadoop fs -ls /tmp/dkl

附圖:

2、完整程式碼

不多做解釋了,直接看程式碼和結果吧(稍微封裝了一下,有其它需求可以參考改寫)

package com.dkl.leanring.spark.hdfs

import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileUtil;
import scala.collection.mutable.ArrayBuffer

/**
 * 主要目的是列印某個hdfs目錄下所有的檔名,包括子目錄下的
 * 其他的方法只是順帶示例,以便有其它需求可以參照改寫
 */
object FilesList {

  def main(args: Array[String]): Unit = {
    val path = "hdfs://ambari.master.com:8020/tmp/dkl"

    println("列印所有的檔名,包括子目錄")
    listAllFiles(path)
    println("列印一級檔名")
    listFiles(path)
    println("列印一級目錄名")
    listDirs(path)
    println("列印一級檔名和目錄名")
    listFilesAndDirs(path)
    //    getAllFiles(path).foreach(println)
    //    getFiles(path).foreach(println)
    //    getDirs(path).foreach(println)
  }

  def getHdfs(path: String) = {
    val conf = new Configuration()
    FileSystem.get(URI.create(path), conf)
  }
  def getFilesAndDirs(path: String): Array[Path] = {
    val fs = getHdfs(path).listStatus(new Path(path))
    FileUtil.stat2Paths(fs)
  }

  /**************直接列印************/

  /**
   * 列印所有的檔名,包括子目錄
   */
  def listAllFiles(path: String) {
    val hdfs = getHdfs(path)
    val listPath = getFilesAndDirs(path)
    listPath.foreach(path => {
      if (hdfs.getFileStatus(path).isFile())
        println(path)
      else {
        listAllFiles(path.toString())

      }
    })
  }
  /**
   * 列印一級檔名
   */
  def listFiles(path: String) {
    getFilesAndDirs(path).filter(getHdfs(path).getFileStatus(_).isFile()).foreach(println)
  }

  /**
   * 列印一級目錄名
   */
  def listDirs(path: String) {
    getFilesAndDirs(path).filter(getHdfs(path).getFileStatus(_).isDirectory()).foreach(println)
  }
  /**
   * 列印一級檔名和目錄名
   */
  def listFilesAndDirs(path: String) {
    getFilesAndDirs(path).foreach(println)
  }

  /**************直接列印************/

  /**************返回陣列************/
  def getAllFiles(path: String): ArrayBuffer[Path] = {
    val arr = ArrayBuffer[Path]()
    val hdfs = getHdfs(path)
    val listPath = getFilesAndDirs(path)
    listPath.foreach(path => {
      if (hdfs.getFileStatus(path).isFile()) {
        arr += path
      } else {
        arr ++= getAllFiles(path.toString())
      }

    })
    arr
  }
  def getFiles(path: String): Array[Path] = {
    getFilesAndDirs(path).filter(getHdfs(path).getFileStatus(_).isFile())
  }
  def getDirs(path: String): Array[Path] = {
    getFilesAndDirs(path).filter(getHdfs(path).getFileStatus(_).isDirectory())
  }
  /**************返回陣列************/

}


3、結果