如何将一个小的字符串列表写入 HDFS 上的文件?



我编写了以下函数,旨在将字符串列表写入HDFS,但是我遇到了一些困难:

import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.io._
import org.apache.hadoop.conf.Configuration
import java.io.BufferedOutputStream
def fileFromList(input: String, outputPath: String) = {
val hdfs = FileSystem.get(new Configuration())
val path = new Path(outputPath)
val output= hdfs.create(path)
val outt = new BufferedOutputStream(output)
outt.write(input.getBytes)
outt.close()
hdfs.close()
}

但是当我尝试使用类型为 List[String] 的输入时,我收到编译错误。

以下是我尝试存储的输入列表示例:

val input = List(
"banana apple strawberry",
"Apple banana strawberry"
)

我想保存在这个确切的文件中:

val outputpath = "/folder/test.YMSL"

有什么想法怎么做吗?

您需要将输入List[String]作为与'n'联接的String加入:

List("banana apple strawberry", "Apple banana strawberry").mkString("n")
res0: String = "banana apple strawberrynApple banana strawberry"

此外,您从FileSystem.create方法创建的FSDataOutputStream实际上有一个write方法,它允许您直接在 hdfs 上写入文件。

因此,无需创建BufferedOutputStream流。


我习惯于保留这个助手:

import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.conf.Configuration
def writeToHdfsFile(content: String, filePath: String): Unit = {
val outputFile = FileSystem.get(new Configuration()).create(new Path(filePath))
outputFile.write(content.getBytes("UTF-8"))
outputFile.close()
}

以及:

def writeToHdfsFile(seq: Seq[String], filePath: String): Unit =
writeToHdfsFile(seq.mkString("n"), filePath)

可以这样称呼:

writeToHdfsFile(
List("banana apple strawberry", "Apple banana strawberry"), 
"/folder/test.YMSL"
)

最新更新