spark源码阅读一-spark读写文件代码分析

本文深入探讨了Spark如何读取和写入文件,重点分析了`sparkcontext.textFile`和`saveAsTextFile`的源码实现。在读取文件时,详细解释了`hadoopFile`和`TextInputFormat`的角色,以及如何根据分区和Block大小进行切分。写文件部分,介绍了如何通过`repartition`和`saveAsTextFile`将数据转化为Text文件并保存到本地或HDFS。
1.读取文件
从本地文件读取sparkcontext.textFile(“abc.txt”)
从hdfs文件读取sparkcontext.textFile("hdfs://s1:8020/user/hdfs/input”)
def textFile(
    path: String,
    minPartitions: Int = defaultMinPartitions): RDD[String] = withScope {
  assertNotStopped()
  hadoopFile(path, classOf[TextInputFormat], classOf[LongWritable], classOf[Text],
    minPartitions).map(pair => pair._2.toString).setName(path)
}
textFile第2个参数是partition个数,默认defaultMinPartitions为2,分2个区。也可以自定义最小分区数。
接下来就是看hadoopFile实现:
def hadoopFile[K, V](
    path: String,
    inputFormatClass: Class[_ <: InputFormat[K, V]],
    keyClass: Class[K],
    valueClass: Class[V],
    minPartitions: Int = defaultMinPartitions): RDD[(K, V)] = withScope {
  assertNotStopped()

  // This is a hack to enforce loading hdfs-site.xml.   
  // See SPARK-11227 for details.   
  FileSystem. getLocal(hadoopConfiguration)

  // A Hadoop configuration can be about 10 KB, which is pretty big, so broadcast it.   
  val confBroadcast = broadcast( new SerializableConfiguration(hadoopConfiguration))
  val setInputPathsFunc = (jobConf: JobConf) => FileInputFormat. setInputPaths(jobConf, path)
  new HadoopRDD(
    this,
    confBroadcast,
    Some(setInputPathsFunc),
    inputFormatClass,
    keyClass,
    valueClass,
    minPartitions).setName(path)
}
这里返回的就是HadoopRDD,RDD最关键的2个信息就是如何分区,以及PreferredLocation。
关于第一个问题分区,我们看看getPartitions
override def getPartitions: Array[Partition] = {
  val jobConf = getJobConf()
  // add the credentials here as this can be called before SparkContext initialized   SparkHadoopUtil. get.
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值