java spark读写hdfs文件,在Spark / Scala中写入HDFS以读取zip文件

该博客介绍了一个使用Spark和Scala编写的程序,用于读取本地ZIP文件,解压缩其内容,并将结果写入新的文件。目前程序能够将输出写入本地文件系统,作者询问如何将输出文件保存到分布式文件系统如HDFS。解决方案提供了使用Hadoop Common库将数据写入HDFS的方法,包括配置文件系统、创建FileSystem对象以及通过FSDataOutputStream写入数据。
摘要由CSDN通过智能技术生成

I am writing a spark/scala program to read in ZIP files, unzip them and write the contents to a set of new files. I can get this to work for writing to the local file system but wondered if there was a way to to write the output files to a distributed file system such as HDFS. Code is shown below`

import java.util.zip.ZipInputStream

import org.apache.spark.input.PortableDataStream

import java.io._

var i =1

sc.binaryFiles("file:///d/tmp/zips/").flatMap((file:(String, PortableDataStream)) => {

val zipStream = new ZipInputStream(file._2.open)

val entry = zipStream.getNextEntry

val iter = scala.io.Source.fromInputStream(zipStream).getLines

val fname = f"/d/tmp/myfile$i.txt"

i = i + 1

val xx = iter.mkString

val writer = new PrintWriter(new File(fname))

writer.write(xx)

writer.close()

iter

}).collect()

`

解决方案

You can easy write data to HDFS using hadoop-common library (if you are using sbt as dependency manangement tool, add thath library to your dependency). With that you can create a FileSystem object :

private val fs = {

val conf = new Configuration()

FileSystem.get(conf)

}

Be sure to configure the FileSystem with your hadoop cluster information (core-site.xml, etc)

Then you can write, for example a String to path (in your case you should deal with streams), on HDFS as following:

@throws[IOException]

def writeAsString(hdfsPath: String, content: String) {

val path: Path = new Path(hdfsPath)

if (fs.exists(path)) {

fs.delete(path, true)

}

val dataOutputStream: FSDataOutputStream = fs.create(path)

val bw: BufferedWriter = new BufferedWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"))

bw.write(content)

bw.close

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值