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



对于我目前正在使用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)

最新更新