Search code examples
javascalazip

How do you read a zipped input stream without writing to a file?


I'm writing a unit test that tests functionality that creates three files zipped together and returns an InputStream (specifically ByteArrayInputStream). I just want to take each file individually, uncompress it, and then make some assertions about the contents. Everything I'm finding online is to write to a file, so how would I do this completely in-mem?

Here is the point I've gotten to:


      val zipIn = new ZipInputStream(zippedStream)

      Stream.continually(zipIn.getNextEntry)
          .takeWhile(_ != null)
          .foreach { entry =>
            val fout = new FileOutputStream(entry.getName)
            val buffer = new Array[Byte](1024)
            Stream.continually(zipIn.read(buffer))
              .takeWhile(_ != -1)
              .foreach(fout.write(buffer, 0, _))
          }

Solution

  • Instead of FileOutputStream, use ByteArrayOutputStream. This class accumulates the data written into an array of bytes that's resized when needed. You can get a copy of the bytes it has accumulates with the toByteArray method.