scalaziozio-streams

Write output of ZIO Stream to file


I am trying to write the results of a ZIO Stream to a file. The following example app takes a sequence of integers, converts them to bytes, compresses them with the gzip transducer, but I cannot figure out how to write them to a file.

I think I need to use ZSink.fromOutputStream, but I am unsure how that fits into the code.

object ZStreamExample extends zio.App {
  val job = (for {
    stream <- ZStream
      .fromIterable(Seq(1,2,3,4))
      .map(value => s"$value")
      .map(value => value.toByte)
      .transduce(gzip())
  } yield stream)

  def run(args: List[String]) = {
    job.runCollect
  }.exitCode
}

Solution

  • I would recommend you to take a closer look to the docs and the api.

    It seems you only need to do something like this:

    object ZStreamExample extends zio.App {
      val job =
        ZStream
          .fromIterable(Seq(1,2,3,4))
          .map(value => s"$value")
          .map(value => value.toByte)
          .transduce(gzip())
          .run(ZSink.fromFile(Paths.get("file.txt")))
    
      def run(args: List[String]) =
        job.exitCde
    }