英文:
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's resized when needed. You can get a copy of the bytes it has accumulates with the `toByteArray` method.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论