對于我目前正在使用 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關于我該怎么做的任何想法?
謝謝你的幫助
uj5u.com熱心網友回復:
用于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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460156.html
下一篇:hiveQL查詢selectclassID,studNamefromtable1wheregrade=Max(grade)groupbyclassID,studName;
