给定一个文件,比如t.gz,它是压缩的,我希望能够逐行读取该文件的内容。
我可以通过以下方式阅读内容:
Source.fromInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(s))))然而,我正在寻找一种以功能范式来处理这些文件的方法,这让我了解了fs2。
如果我解压缩文件,我可以这样做:
import cats.effect._
import fs2.io.file.{Files, Path}
import fs2.{Stream, text, compression, io}
object Main extends IOApp.Simple {
def doThing(inPath: Path): Stream[IO, Unit] = {
Files[IO]
.readAll(inPath)
.through(text.utf8.decode)
.through(text.lines)
.map(line => line)
.intersperse("\n")
.through(text.utf8.encode)
.through(io.stdout)
}
val run = doThing(Path("t")).compile.drain
}为了简单起见,我们最终会去控制台。
如果我把它放在压缩格式中,我似乎找不到任何地方显示这些操作是如何结合在一起的,从而提供了一个流。
fs2似乎有一个压缩对象(https://www.javadoc.io/doc/co.fs2/fs2-docs_2.13/latest/fs2/compression/Compression.html),它似乎应该执行所需的操作,但是如果它还没有解决如何集成的问题。
因此,问题是:如何将压缩后的文件读入流中,以便在功能范例中使用fs2?
发布于 2022-08-31 00:30:44
你可能想要这个:
object Main extends IOApp.Simple {
def doThing(inPath: Path): Stream[IO, Unit] = {
Files[IO]
.readAll(inPath)
.through(Compression[IO].gunzip())
.flatMap(_.content)
.through(text.utf8.decode)
.through(text.lines)
.map(line => line)
.intersperse("\n")
.through(text.utf8.encode)
.through(io.stdout)
}
override final val run =
doThing(Path("t")).compile.drain
}https://stackoverflow.com/questions/73549608
复制相似问题