首页 > 解决方案 > 从 HDFS 读取文件,Scala Spark

问题描述

我正在尝试从 HDFS 读取文件,但我在这里遇到了问题。该文件不存在,因此我必须检查是否存在。如果文件存在,我会读取该文件,否则我会读取一个空的 DF

所以我正在尝试的是:

val fs: FilySystem = FileSystem.get(new URI(path), new Configuration())
if (fs.exists(new org.apache.hadoop.fs.Path(s"$Path"))) {
    val df6 = spark.read.parquet(path)
} else {
    val df6 = df1.limit(0)
}
val df6.show()

但是我在 Jupyter 上收到以下错误:

Message: <console>:28: error: not found: type FileSystem

我做错了什么?

标签: scalaapache-sparkhadoophdfs

解决方案


Try something like this (with your adjustment) -

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.fs.Path
import java.net.URI
import scala.io.Source
    
val hdfs = FileSystem.get(new URI("hdfs://cluster:8020/"), new Configuration())
val path = new Path("/HDFS/FILE/LOCATION")
val stream = hdfs.open(path)
val temp = Source.fromInputStream(stream).getLines()

推荐阅读