电脑疯子技术论坛|电脑极客社区

 找回密码
 注册

QQ登录

只需一步,快速开始

[windows应用教程] 怎么在Windows上使用Intellij编写Spark程序访问文件?

[复制链接]
zhaorong 发表于 2018-4-18 11:07:50 | 显示全部楼层 |阅读模式

在Windows上使用Intellij编写Spark程序访问文件

访问txt文件


1.使用Spark访问的文件类型有很多种,包括txt,csv,json等。下面依次使用做访问

2.本程序使用maven+intellij+spark+windows编写

访问.txt文件

  1. import org.apache.spark.{SparkConf, SparkContext}
  2. object ReadTxt {
  3.   def main(args:Array[String]): Unit ={
  4.     val conf = new SparkConf().setAppName("ReadCSV").setMaster("local")//必须要加上.setAppName(),
  5. 否则报错
  6.     val sc = new SparkContext(conf)
  7.     val input = sc.textFile("C:\\Users\\enmonster\\Desktop\\information.txt")
  8.     input.take(10).foreach(println)
  9.   }
  10. }
复制代码


读取的文件以及执行结果均如下:

  1. name,LittleLawson
  2. age,20
  3. gender,male
复制代码

访问.csv文件


  1. import java.io.StringReader
  2. import com.opencsv.CSVReader
  3. import org.apache.spark.rdd.RDD
  4. import org.apache.spark.{SparkConf, SparkContext}
  5. case class Person(name: String, age: Int,gender:String)
  6. object ReadCSV {
  7.   def main(args:Array[String]): Unit ={
  8.     val conf = new SparkConf().setAppName("ReadCSV").setMaster("local")//
  9.     val sc = new SparkContext(conf)
  10.     val input = sc.textFile("C:\\Users\\enmonster\\Desktop\\information.csv")
  11.     val result: RDD[Array[String]] = input.map { line =>
  12.       line.split(",",-1)
  13.       val reader = new CSVReader(new StringReader(line))
  14.       reader.readNext()
  15.     }
  16.     result.foreach(print)//打印出来的是String对象的hashcode
  17.     result.foreach(x => x.foreach(print))//String对象遍历出来的值 --lamada表达式
  18.     //result.foreach(_.foreach(println(_)))//上式的简写
  19.   }
  20. }
复制代码





您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|VIP|电脑疯子技术论坛 ( Computer madman team )

GMT+8, 2025-2-3 20:55

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表