如何使用scala从hdfs目录中删除所有文件

How to delete all files from hdfs directory with scala

对于我目前正在使用 Scala 和 Spark 进行的项目,我必须编写一个代码来检查我正在处理的 hdfs 目录是否为空,如果不是,我必须从中删除所有文件目录。

在将我的代码部署到 Azur 之前,我正在使用我计算机上的本地目录对其进行测试。

我开始于:创建一个方法来删除该目录中的所有文件。这就是我现在拥有的:

object DirectoryCleaner {


  val spark:SparkSession = SparkSession.builder()
    .master("local[3]")
    .appName("SparkByExamples.com")
    .getOrCreate()

  val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
  val srcPath=new Path("C:\Users\myuser\Desktop\test_dir\file1.csv")

  def deleFilesDir(): Unit = {
    if(fs.exists(srcPath) && fs.isFile(srcPath))
      fs.delete(srcPath, true)
  }


}

使用此代码,我可以删除单个文件 (file1.csv)。我希望能够以这种方式定义我的路径 val srcPath=new Path("C:\Users\myuser\Desktop\test_dir")(不指定任何文件名),并且只删除 test_dir 目录中的每个文件。知道我该怎么做吗?

感谢您的帮助

使用fs.listFiles获取一个目录下的所有文件,然后在删除它们的同时循环遍历它们。此外,将 recursive 标志设置为 false,这样您就不会递归到目录中。

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}

def deleteAllFiles(directoryPath: String, fs: FileSystem): Unit = {

  val path = new Path(directoryPath)

  // get all files in directory
  val files = fs.listFiles(path, false)

  // print and delete all files
  while (files.hasNext) {
    val file = files.next()
    fs.delete(file.getPath, false)
  }

}

// Example for local, non HDFS path 
val directoryPath = "file:///Users/m_vemuri/project"
val fs = FileSystem.get(new Configuration())
deleteAllFiles(directoryPath, fs)