如何将scala fs2 stream转换为字符串?

时间:2018-01-25 10:19:24

标签: scala fs2

我想知道如何将Scala fs2 Stream转换为字符串,来自fs2 github readme示例:

def converter[F[_]](implicit F: Sync[F]): F[Unit] = {
  val path = "/Users/lorancechen/version_control_project/_unlimited-works/git-server/src/test/resources"

  io.file.readAll[F](Paths.get(s"$path/fs.txt"), 4096)
    .through(text.utf8Decode)
    .through(text.lines)
    .filter(s => !s.trim.isEmpty && !s.startsWith("//"))
    .map(line => fahrenheitToCelsius(line.toDouble).toString)
    .intersperse("\n")
    .through(text.utf8Encode)
    .through(io.file.writeAll(Paths.get(s"$path/fs-output.txt")))
    .compile.drain

}

// at the end of the universe...
val u: Unit = converter[IO].unsafeRunSync()

如何将结果发送到String而不是另一个文件?

2 个答案:

答案 0 :(得分:2)

如果您希望在流中投放所有String元素,可以使用runFold来实现它。一个简单的例子:

def converter[F[_]](implicit F: Sync[F]): F[List[String]] = {
  val path = "/Users/lorancechen/version_control_project/_unlimited-works/git-server/src/test/resources"

  io.file.readAll[F](Paths.get(s"$path/fs.txt"), 4096)
    .through(text.utf8Decode)
    .through(text.lines)
    .filter(s => !s.trim.isEmpty && !s.startsWith("//"))
    .runFold(List.empty[String]) { case (acc, str) => str :: acc }
}

然后:

val list: List[String] = converter[IO].unsafeRunSync()

答案 1 :(得分:0)

如果您有Stream[F, String],则可以调用.compile.string将流转换为F[String]

val s: Stream[IO, String] = ???
val io: IO[String] = s.compile.string
val str: String = io.unsafeRunSync()