Spark打印每个split及其对应文件

本文展示了如何使用 Apache Spark 从 Hadoop 分布式文件系统 (HDFS) 中读取数据。通过示例代码介绍了如何配置 Spark 任务来加载特定路径下的文件,并利用 Hadoop 的 TextInputFormat 来划分输入数据。最终输出了每个数据切片的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.apache.hadoop.io.LongWritable
import org.apache.hadoop.io.Text
import org.apache.hadoop.mapred.{FileSplit, TextInputFormat}
import org.apache.spark.rdd.HadoopRDD
import org.apache.hadoop.mapred.InputSplit  

var rdd=sc.hadoopFile("hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test", classOf[TextInputFormat], classOf[LongWritable], classOf[Text], sc.defaultMinPartitions)
val hadoopRdd = rdd.asInstanceOf[HadoopRDD[LongWritable, Text]]


hadoopRdd.mapPartitionsWithInputSplit((inputSplit:InputSplit,iterator:Iterator[(LongWritable, Text)]) =>{  
val file = inputSplit.asInstanceOf[FileSplit]  
var fileSet:Set[String] = Set()
fileSet += file.getPath.toString()
Seq("split,file:"+fileSet.mkString(";")).iterator
}  
).collect().foreach(println)

打印内容如下:

split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000000_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000001_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000002_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000003_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000004_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000005_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000006_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000007_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000008_0
split,file:hdfs://namenode:9000/home/hdp-ads-audit/dubhe_data/hive//tmp/test/dt=2017-03-15/000009_0
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值