我想知道如何将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而不是另一个文件?
答案 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()