文章目录
1.在hdfs的/user/spark/in/目录下建一个in.txt文件
分析如下:
(1).我们需要现在hdfs中创建文件所需目录。
1>创建文件夹
[e93b8f root@master ~]$ hdfs dfs -mkdir /user
[e93b8f root@master ~]$ hdfs dfs -mkdir /user/spark/
[e93b8f root@master ~]$ hdfs dfs -mkdir /user/spark/in
2>也可通过命令创建多级目录。
[ebdfc5 root@master ~]$ hdfs dfs -mkdir -p /user/spark/in/
[ebdfc5 root@master ~]$ hdfs dfs -ls /user/spark/in/
3>通过命令查看是否创建成功
[ebdfc5 root@master ~]$ hdfs dfs -ls /user/spark/
(2).在根目录创建in.txt文件并将其传到hdfs中
1>首先创建txt文件
[e93b8f root@master ~]$ vim in.txt
在文件中输入内容
hello world
ni hao
2>通过pwd查看本地文件所在路径
[ebdfc5 root@master ~]$ pwd
3>文件创建成功之后,将本地的in.txt文件上传至hdfs中。
hadoop fs -put /root/in.txt hdfs:/user/spark/in/
4> 在hdfs中查看是否已经存在。
2.在spark-shell中编写WordCount代码和运行。
1>启动spark-shell
[131ba4 root@master ~]$ spark-shell
2>写入wordcount的scala代码并运行
scala> val file=sc.textFile("hdfs://master:8020/user/spark/in/in.txt")
scala> val count=file.flatMap(line => line.split(" ")).map(word =>(word,1)).reduceByKey(_+_)
scala> count.collect()