2017-03-11 52 views
0

简单的问题一个文本文件: 对于以下RDD我要打印输出的文本文件格式如下和头(用户ID,MovieID,Pred_rating)打印RDD与头

scala> final_predictions_adjusted.sortByKey().first 
res61: ((Int, Int), Double) = ((1,1172),1.8697903970770442) 

够简单。对?所以我用这个函数:

def print_outputfile(final_predictions_adjusted:RDD[((Int, Int), Double)])={ 
    val writer = new FileWriter(new File("output.txt")) 
    writer.write("UserID,MovieID,Pred_rating") 
    final_predictions_adjusted.sortByKey().foreach(x=>{writer.write(x.toString())}) 
    writer.close() 
    } 

上述功能不与下面的错误

caused by: java.io.NotSerializableException: java.io.FileWrite 

回答

0

这工作就像甜蜜的领主会:

def print_outputfile(final_predictions_adjusted:RDD[((Int, Int), Double)])={ 
    val writer = new FileWriter(new File("output.txt")) 
    writer.write("UserID,MovieID,Pred_rating\n") 
    final_predictions_adjusted.sortByKey().collect().foreach(x=>{writer.write(x._1._1+","+x._1._2+","+x._2+"\n")}) 
    writer.close() 
    } 
+0

'collect'结果将只在驱动程序中。好的,只要结果足够小以适应那里,但不适用于大数据集 –

0

与您的代码的FileWriter对象将被发送到所有节点并行进行,这不工作不适用于本地文件的引用。因此你得到NotSerializableException。

您通常由saveAsTextFile的RDD保存到一个文件:

final_predictions_adjusted.sortByKey().map(e=> (e._1._1,e._1._2,e._2)).saveAsTextFile("output.dir") 

此写出多份文件。您可以添加标题并稍后手动合并这些部分。

+0

哇。更好。如果我使用'final_predictions_adjusted.sortByKey()。collect()。foreach(x => {writer.write(x.toString())'thans来解释错误 –