• Spark RDD 多文件输入


    1.将多个文本文件读入一个RDD中

      

           SparkConf conf=new SparkConf()
                   .setMaster("local")
                   .setAppName("save");
           JavaSparkContext sc=new JavaSparkContext(conf);
           
           JavaRDD<String>  lines=sc.textFile("student*");
           lines.foreach(new VoidFunction<String>(){
    
            @Override
            public void call(String arg0) throws Exception {
                // TODO Auto-generated method stub
                System.out.println(args);
                
            }
               
           });
           
        }

       textFile的参数可以支持通配符哦!!!很强大吧。事实上,这个东西确实很强大:

    public RDD<java.lang.String> textFile(java.lang.String path,
                                 int minPartitions)
    Read a text file from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI, and return it as an RDD of Strings.

    他可以从hdfs中读取数据,可以从本地文件系统读取数据(之不多此时要求所有节点都要有这个文件),或者任何hadoop支持的文件系统。

    2.将一个RDD保存到文件中。

       SparkConf conf=new SparkConf()
                   .setMaster("local")
                   .setAppName("save");
           JavaSparkContext sc=new JavaSparkContext(conf);
           
           JavaRDD<String>  lines=sc.textFile("student*");
    
    //保存到hdfs lines.saveAsTextFile(
    "hdfs://spark2:9000/francis/spark-core/studentsRDD.txt");

    ok,让我们查看一下hdfs上的文件吧:

    hadoop fs -ls -h /francis/spark-core/studentsRDD.txt/

    内容如下:

    Found 4 items
    -rw-r--r--   3 francis supergroup          0 2016-03-10 18:58 /francis/spark-core/studentsRDD.txt/_SUCCESS
    -rw-r--r--   3 francis supergroup         38 2016-03-10 18:58 /francis/spark-core/studentsRDD.txt/part-00000
    -rw-r--r--   3 francis supergroup         38 2016-03-10 18:58 /francis/spark-core/studentsRDD.txt/part-00001
    -rw-r--r--   3 francis supergroup         38 2016-03-10 18:58 /francis/spark-core/studentsRDD.txt/part-00002

    可以发现,每一个partition保存到一个文件中去了。

    注意:在windows eclipse中调用saveAsTextFile时,如果将数据保存到window本地文件,会出现错误!!!!!

    想要测试这种情况,还是去linux吧。

     

    调用saveAsTextFile将数据保存到外部文件系统中了,那么如何在将他们到RDD中呢?只需要调用textFile并传入当时保存的那个文件名就ok了。

    3.将RDD保存到一个文件中

      上面看到了,每一个partition会被保存到要给单独的文件中去。如何让所有partition都保存到一个文件中呢?可以考虑如下两种思路:

      第一种方法,对rdd调用collect(),此时返回的是要给array,然后将array保存到文件中。

      第二张方法,并不推荐,他可能会极大的降低性能:先调用coalesce(1),然后再saveAsTextFile。

    是否真的需要保存到一个文件中?这个需要仔细商榷,如果数据量比较大,保存到一个文件的性能会大大降低。

    作者:FrancisWang

    邮箱:franciswbs@163.com
    出处:http://www.cnblogs.com/francisYoung/
    本文地址:http://www.cnblogs.com/francisYoung/p/5263179.html
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    Python汉字转换成拼音
    python之Tkinter控件学习
    python 函数式编程:高阶函数,map/reduce
    python的高级特性:切片,迭代,列表生成式,生成器,迭代器
    python tkinter Listbox用法
    python函数定义语法总结
    Cmder 快捷键
    录音水波动画
    图片截取部分显示
    移动web在ios和android下点击元素出现阴影问题
  • 原文地址:https://www.cnblogs.com/francisYoung/p/5263179.html
Copyright © 2020-2023  润新知