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

微信扫一扫 分享朋友圈

已有 1872 人浏览分享

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

[复制链接]
1872 0

在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. }
复制代码






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

本版积分规则

1

关注

0

粉丝

9021

主题
精彩推荐
热门资讯
网友晒图
图文推荐

Powered by Pcgho! X3.4

© 2008-2022 Pcgho Inc.