我有一个 Array[String]
,其中包含一些文件的路径。
该数组是自动生成的,因此无法保证文件存在。
我想读取所有这些路径,将现有路径加载到 RDD 中,并忽略不存在的路径。
我已尝试执行以下操作:
import scala.util.Try
val arrayOfFilePaths: Array[String] = ["path1", "path2", "path3", "path4"]
val allRecords = sc.union(arrayOfFilePaths.map(p => Try(sc.textFile(p))).filter(_.isSuccess).map(_.get))
但看起来它没有成功避免不存在的文件,当我尝试 allRecords.collect()
时出现以下错误:
Input path does not exist: file:/path/to/unexistingFile
at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:285)
这里有什么问题的提示吗?
最佳答案
好的,我想出了一个解决方案。
我在加载文件之前过滤了数组。
import java.nio.file.{Paths, Files}
val filteredPaths = arrayOfFilePaths.filter(p => Files.exists(Paths.get(p))).mkString(",")
然后我可以加载这些文件
val allRecords = sc.textFile(filteredPaths)
关于apache-spark - Spark : read multiple files and ignore the missing ones,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890818/