在Spark中,如何在没有RDD的情况下在Hadoop上编写文件?
问题描述:
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()
答
为什么不做以下几点?
val strings = sc.parallelize(Seq("hello", "there"), <numPartitions>)
strings.saveAsTextFile("<path-to-file>")
否则您可能需要查看hadoop API来编写文件并从您的驱动程序显式调用该代码。
答
假设你有一个绑定到一个sc
SparkContext
:
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()
注:为了简单起见,没有代码以关闭作家异常的情况。
thx。我可以使用“s3n://your-output-bucket/result.txt”网址,而不是“hdfs:// localhost:9000 // tmp/hello.txt”吗? –