Lirsoon 2017-10-21 04:07 采纳率: 0%
浏览 2122

从hdfs中读取数据并用spark操作时出现问题

我从集群环境的hdfs中读取数据,然后处理数据时出现问题,在循环里面添加的对象在循环外就没有了,初学spark和scala,请大佬指点.
object Test {

case class Passenger(name: String, txn_date: String, txn_time: String, txn_station: String, ticket_type: String, trans_code: String, sub: String, txn_station_id: String)

def main(args: Array[String]): Unit = {
val inputFile = "hdfs://Master:9000/user/hadoop/input/tmp.txt"
val conf = new SparkConf().setAppName("WordCount")
val sc = new SparkContext(conf)

val text = sc.textFile(inputFile) //25 lines like "000025643       "    "20141201"  "060912"    "0328"  "88"    "22"    "" from hdfs
val Passengers = new ArrayBuffer[Passenger]()
for (line <- text) {
  val points = for (i <- 0 until (line.length) if (line.charAt(i) == '"')) yield {
    i
  }
  val items = for (i <- 0 until (points.length) if (i % 2 == 0)) yield {
    if (!line.slice(points(i).toString.toInt + 1, points(i + 1).toString.toInt).equals("")) {
      line.slice(points(i).toString.toInt + 1, points(i + 1).toString.toInt).trim
    }
    else
      "null"
  }
  val tmp:Passenger=new Passenger(items(0).trim, items(1), items(2), items(3), items(4), items(5), "null", items(6))
  println(tmp) //it is Passenger(000026853,20141201,060921,0325,88,21,null,null) [no problem]
  Passengers.append(tmp)
  println(Passengers.length) //1,2,3.....25 [no problem]
}
println("----------------------------" + Passengers.length) //it is 0!!!! why?
val passengersArray = Passengers.toArray

val customersRDD = sc.parallelize(passengersArray)
val customersDF = customersRDD.toDF()

}
}


  • 写回答

1条回答

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-10-27 15:50
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能