命令及结果示例
scala> val lines = sc.textFile("README.md")
lines: org.apache.spark.rdd.RDD[String] = README.md MapPartitionsRDD[1] at textFile at <console>:24
scala> lines.count()
res0: Long = 99
scala> lines.first()
res1: String = # Apache Spark
其中 README.md 默认是spark安装路径bin/下的README.md文件,多种读取方式,
1、本地文件:val lines =sc.textFile("file:///root/bus_info.txt")
还可以通过通配符的形式加载多个文件或者加载多个目录下面的所有文件
假设我的数据结构为先按天分区,再按小时分区的,在hdfs上的目录结构类似于:
/user/hdfs/input/dt=20130728/hr=00/
/user/hdfs/input/dt=20130728/hr=01/
...
/user/hdfs/input/dt=20130728/hr=23/
具体的数据都在hr等于某个时间的目录下面,现在我们要分析20130728这一天的数据,我们就必须把这个目录下面的所有hr=*的子目录下面的数据全部装载进RDD,于是我们可以这样写:sc.textFile("hdfs://n1:8020/user/hdfs/input/dt=20130728/hr=*/"),注意到hr=*,是一个模糊匹配的方式。
2、hdfs文件中读取:val lines2 =sc.textFile("hdfs://localhost:8082/user/spark/bus_info.txt")