1

我编写了以下函数,旨在将字符串列表写入 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"

任何想法如何做到这一点?

4

1 回答 1

1

您需要将您的输入List[String]作为join Stringwith 加入'\n'

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

此外,FSDataOutputStream您从该FileSystem.create方法创建的实际上有一个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"
)
于 2018-05-22T12:35:00.357 回答