apache-spark - Spark : read multiple files and ignore the missing ones

标签 apache-spark

我有一个 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/

相关文章:

python - 在 Spark 中广播用户定义的类

apache-spark - Kafka 主题分区到 Spark 流

apache-spark - 星火流不工作

apache-spark - 从云中的 Web 应用程序调用 Jupyter Notebook

python - 在 MacBook 上安装 pyspark

scala - 为什么启动 StreamingContext 失败并显示 "IllegalArgumentException: requirement failed: No output operations registered, so nothing to execute"?

scala - 在 Spark 中使用带有未定义框架的 WindowSpec 是否安全?

scala - 使用 SBT : Invalid or corrupt jarfile 构建 Apache Spark

python - 在 Python 中从 Spark DataFrame 创建 labeledPoints

python - 如何在 Jupyter Notebook 中正确设置 SparkContext 的配置?