我想知道如何将 Scala fs2 Stream 转换为字符串,来自 fs2 github 自述文件示例:
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()
Run Code Online (Sandbox Code Playgroud)
如何将结果获取到字符串而不是另一个文件?
如果您有Stream[F, String],您可以调用.compile.string将流转换为F[String].
val s: Stream[IO, String] = ???
val io: IO[String] = s.compile.string
val str: String = io.unsafeRunSync()
Run Code Online (Sandbox Code Playgroud)
如果您想让所有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 }
}
Run Code Online (Sandbox Code Playgroud)
进而:
val list: List[String] = converter[IO].unsafeRunSync()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2719 次 |
| 最近记录: |