首页 > 解决方案 > 通过 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"))

标签: amazon-web-servicesapache-sparkamazon-s3apache-spark-sqlhdfs

解决方案


您可以使用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 和本地文件系统,您可以编写单元测试


推荐阅读