2016-09-26 95 views
0

Spark Spark RDD具有saveAsTxtFile功能。但是,我如何打开一个文件并向Hadoop商店写入一个简单的字符串?在Spark中,如何在没有RDD的情况下在Hadoop上编写文件?

val sparkConf: SparkConf = new SparkConf().setAppName("example") 
val sc: SparkContext = new SparkContext(sparkConf) 

sc.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "...") 
sc.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "...") 

val lines: RDD[String] = sc.textFile("s3n://your-output-bucket/lines.txt") 
val lengths: RDD[Int] = lines.map(_.length) 
lengths.saveAsTextFile("s3n://your-output-bucket/lenths.txt") 

val numLines: Long = lines.count 
val resultString: String = s"numLines: $numLines" 
// how to save resultString to "s3n://your-output-bucket/result.txt" 

sc.stop() 

回答

1

为什么不做以下几点?

val strings = sc.parallelize(Seq("hello", "there"), <numPartitions>) 
strings.saveAsTextFile("<path-to-file>") 

否则您可能需要查看hadoop API来编写文件并从您的驱动程序显式调用该代码。

1

假设你有一个绑定到一个scSparkContext

import java.io.{BufferedWriter, OutputStreamWriter} 

val hdfs = org.apache.hadoop.fs.FileSystem.get(sc.hadoopConfiguration) 

val outputPath = 
    new org.apache.hadoop.fs.Path("hdfs://localhost:9000//tmp/hello.txt") 

val overwrite = true 

val bw = 
    new BufferedWriter(new OutputStreamWriter(hdfs.create(outputPath, overwrite))) 
bw.write("Hello, world") 
bw.close() 

注:为了简单起见,没有代码以关闭作家异常的情况。

+0

thx。我可以使用“s3n://your-output-bucket/result.txt”网址,而不是“hdfs:// localhost:9000 // tmp/hello.txt”吗? –

相关问题