从现有的 OutputStream 创建 Java-Zip-Archive [英] Create Java-Zip-Archive from existing OutputStream
问题描述
如果我不想将生成的存档写入磁盘而是将其发送到其他地方,是否可以在 Java 中创建 Zip-Archive?
Is it possible to create a Zip-Archive in Java if I do not want to write the resulting archive to disk but send it somewhere else?
这个想法是,当您想通过 HTTP(例如从数据库 Blob 或任何其他数据存储)将 Zip-Archive 发送给用户时,在磁盘上创建文件可能是一种浪费.
The idea is that it might be a waste to create a file on disk when you want to send the Zip-Archive to a user via HTTP (e.g. from a Database-Blob or any other Data-Store).
我想创建一个
java.util.zip.ZipOutputStream
或
apache.commons.ZipArchiveOutputStream
Feeder 是来自我的 Subversion 存储库的 ByteArrayOutputStream
where the Feeder would be a ByteArrayOutputStream coming from my Subversion Repository
推荐答案
是的,这绝对有可能!
使用 ZipOutputStream
上的 putNextEntry
方法创建您的 Zip 条目,然后通过调用 write
将字节放入 zip 文件中ZipOutputStream
.对于该方法的参数 byte[]
,只需使用其 toByteArray
方法从 ByteArrayOutputStream
中提取它们即可.
Create your Zip entry using the putNextEntry
method on the ZipOutputStream
then put the bytes into the file in the zip by calling write
on the ZipOutputStream
. For the parameter for that method, the byte[]
, just extract them from the ByteArrayOutputStream
with its toByteArray
method.
并且 ZipOutputStream
可以发送到任何地方,因为它的构造函数只需要一个 OutputStream
所以可以是例如你的 HTTP 响应.
And the ZipOutputStream
can be sent anywhere, as its constructor just takes an OutputStream
so could be e.g. your HTTP response.
这篇关于从现有的 OutputStream 创建 Java-Zip-Archive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!