amazon-web-services - 通过 Spark 对本地文件系统中是否存在文件进行单元测试
问题描述
我能够通过 spark 在 EMR 集群中成功测试以下代码。但是我无法在 intelliJ 中使用本地文件系统编写单元测试用例。任何人都可以帮助我如何在下面的代码中指定 intelliJ 中的本地文件系统。
在 EMR 集群中工作
FileSystem.get(new URI("s3n://bucket"), sc.hadoopConfiguration).exists(new Path("/path_to_check"))
在 IntelliJ 中不起作用。它总是返回 false
FileSystem.get(new URI("file://somelocal/bucket"), sc.hadoopConfiguration).exists(new Path("/some/local/path_to_check"))
解决方案
您可以使用org.apache.hadoop.fs.FileSystem
def isFileExists(path: String, pattern: String)(implicit spark: SparkSession): Boolean = {
val fixedPath = path.stripSuffix("/") + "/"
val conf = spark.sparkContext.hadoopConfiguration
val fs = FileSystem.get(new URI(path), conf)
val reg = new Regex(pattern)
try {
val files = fs.listFiles(new Path(fixedPath), true)
var flag = false
// hack because listFiles returns RemoteIterator which not an inheritor of java.util.Iterator
while (files.hasNext) {
reg.findFirstMatchIn(files.next().toString) match {
case Some(_) => flag = true
case None =>
}
}
flag
} catch {
// if dir doesn't exist
case _: java.io.FileNotFoundException => false
case e: Throwable => throw e
} finally {
fs.close()
}
}
它适用于 s3、hdfs 和本地文件系统,您可以编写单元测试
推荐阅读
- java - 从文件中获取整数值到数组
- c# - 我怎样才能让我的角色在移动时跳来跳去?
- mysql - 如何在 sequlize 中创建类似于 mysql 数据类型的列?
- python - 耦合方程组 - 来自 scipy 的 fsolve 的错误答案
- reactjs - React.js:调用 API 时在 index.js 上使用覆盖微调器
- c++ - 传递抽象 X 的子类的对象,并实例化抽象 X 的子类类型的字段
- javascript - 隐藏一个当没有给定条件时
- javascript - Discord.js 另一个嵌入的嵌入反应
- java - 无法正确拆分子字符串以进行编辑
- python - 为 python 计算器创建测试用例