如何在不写入文件的情况下读取压缩输入流?

huangapple go评论67阅读模式
英文:

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

问题

我正在编写一个单元测试,用于测试创建将三个文件一起压缩并返回InputStream(具体来说是ByteArrayInputStream)的功能。我只想逐个提取每个文件,解压缩它,然后对内容进行一些断言。我在网上找到的所有内容都是关于写入文件的,那么我该如何完全在内存中操作?

以下是我已经完成的部分:


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, _))
}
英文:

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, _))
          }

</details>


# 答案1
**得分**: 4

使用[ByteArrayOutputStream](https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html)代替FileOutputStream。这个类将写入的数据累积到一个字节数组中,并在需要时调整大小。您可以使用`toByteArray`方法获得累积的字节的副本。

<details>
<summary>英文:</summary>

Instead of FileOutputStream, use [ByteArrayOutputStream](https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html). This class accumulates the data written into an array of bytes that&#39;s resized when needed. You can get a copy of the bytes it has accumulates with the `toByteArray` method.

</details>



huangapple
  • 本文由 发表于 2020年4月10日 01:07:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61126472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定