如何使用fs2从当前流文件中删除过滤
行并获取过滤行数作为返回类型?
例如:如果 old.txt
包含由换行符 (\n) 分隔的字符串:
john
sam
chen
yval
....
和val myList = List("chen","yval")
。
def converter[F[_]](implicit F: Sync[F]): F[Unit] =
io.file.readAll[F](Paths.get("testdata/old.txt"), 4096)
.through(text.utf8Decode)
.through(text.lines)
.filter(s => myList.contains(s))//remove this from the old file and write to new file
.intersperse("\n")
.through(text.utf8Encode)
.through(io.file.writeAll(Paths.get("testdata/new.txt")))
.compile.drain
// at the end of the universe...
val u: Unit = converter[IO].unsafeRunSync()
最佳答案
您可以使用observe method Stream 类的。
您正在寻找一个函数def converter[F[_]: Sync]: F[Int]
,
它产生一个计算F[Int]
,其结果(类型为Int
)是过滤的行数,其效果是将这些行写入输出文件。为了遵循管道类比,您希望将过滤后的流馈送到两个输出,一个用于结果,另一个用于效果。
您可以使用函数 observe 来完成此操作,定义为
def observe(sink: Sink[F, O])(implicit F: Effect[F], ec: ExecutionContext): Stream[F, O]
Sink[F,O]
是函数 Stream[F, O] => Stream[F, Unit]
的别名。在您的情况下,接收器是将过滤后的流写入输出文件的代码部分:
def writeToFile[F[_]: Sync]: Sink[F, String] =
_.intersperse("\n")
.through(text.utf8Encode)
.through(io.file.writeAll(Paths.get("testdata/new.txt")))
另一个输出是减少,或者更确切地说折叠,
def converter[F[_]](implicit F: Effect[F], ec: ExecutionContext): F[Int] =
io.file.readAll[F](Paths.get("testdata/old.txt"), 4096)
.through(text.utf8Decode)
.through(text.lines)
.filter(s => myList.contains(s))
.observe(writeToFile[F])
.compile
.fold[Int](0)( (c, _) => c+1)
}
注意:对于此解决方案,您需要将 F
的类型类限制为 Effect
,并且需要使用 执行上下文
。 fold
在ToEffect
中定义。类(class)。
关于scala - 使用 scala fs2 文件流从文件中删除过滤行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49823684/