使用 fs2 将 URL 流式传输到本地文件

2024-01-05

使用 fs2(版本 1.0.4)和 cats-effectIO,我可以将 URL 流式传输到本地文件,

import concurrent.ExecutionContext.Implicits.global

def download(spec: String, filename: String): Stream[IO, Unit] = 
  io.readInputStream((new URL(spec).openConnection.getInputStream), 4096, global, true)
    .through(io.file.writeAll(Paths.get(filename), global))

但是,此代码片段在完成时不会返回有关该过程的任何信息。最重要的是,除了知道操作成功或失败之外,我还想知道如果操作成功则读取了多少字节。我不想检查新文件大小来获取此信息。另一方面,如果操作失败,我想知道是什么原因导致失败。

I tried attempt但我无法解决将原始字节写入新文件的后续步骤。请指教。谢谢


你可能想玩一下observe。我确信有更好的方法来做到这一点,但这里有一个例子可以帮助您摆脱困境:

编译并运行的原始代码:

import fs2.io
import cats.effect.{IO, ContextShift}
import concurrent.ExecutionContext.Implicits.global

import java.net.URL
import java.nio.file.Paths

object Example1 {
  implicit val contextShift: ContextShift[IO] = IO.contextShift(global)

  def download(spec: String, filename: String): fs2.Stream[IO, Unit] =
    io.readInputStream[IO](IO(new URL(spec).openConnection.getInputStream), 4096, global, closeAfterUse=true)
      .through(io.file.writeAll(Paths.get(filename), global))

  def main(args: Array[String]): Unit = {
    download("https://isitchristmas.com/", "/tmp/christmas.txt")
      .compile.drain.unsafeRunSync()
  }
}

使用observe来计算字节数:

import fs2.io
import cats.effect.{IO, ContextShift}
import concurrent.ExecutionContext.Implicits.global

import java.net.URL
import java.nio.file.Paths

object Example2 {
  implicit val contextShift: ContextShift[IO] = IO.contextShift(global)

  final case class DlResults(bytes: Long)

  def download(spec: String, filename: String): fs2.Stream[IO, DlResults] =
    io.readInputStream[IO](IO(new URL(spec).openConnection.getInputStream), 4096, global, closeAfterUse = true)
      .observe(io.file.writeAll(Paths.get(filename), global))
      .fold(DlResults(0L)) { (r, _) => DlResults(r.bytes + 1) }

  def main(args: Array[String]): Unit = {
    download("https://isitchristmas.com/", "/tmp/christmas.txt")
      .compile
      .fold(()){ (_, r) => println(r)}
      .unsafeRunSync()
  }
}

Output:

> DlResults(42668)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 fs2 将 URL 流式传输到本地文件 的相关文章

随机推荐