我想知道如何将Scala fs2流转换为string,从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()如何获得结果字符串而不是另一个文件?
发布于 2018-01-25 11:05:30
如果您想让所有的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()发布于 2019-11-28 08:30:03
如果您有一个Stream[F, String],您可以调用.compile.string将您的流转换为F[String]。
val s: Stream[IO, String] = ???
val io: IO[String] = s.compile.string
val str: String = io.unsafeRunSync()https://stackoverflow.com/questions/48440474
复制相似问题