Create Java-Zip-Archive from existing OutputStream

2020-07-10 12:01发布

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?

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).

I would like to create a

java.util.zip.ZipOutputStream 

or a

apache.commons.ZipArchiveOutputStream

where the Feeder would be a ByteArrayOutputStream coming from my Subversion Repository

4条回答
冷血范
2楼-- · 2020-07-10 12:31

Something like that would work:

ZipOutputStream zs = new ZipOutputStream(outputStream) ;
ZipEntry e = new ZipEntry(fileName);
zs.putNextEntry(e);
zs.write(...);
zs.close();
查看更多
叛逆
3楼-- · 2020-07-10 12:35

Use Apache Commons Compress:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.16.1</version>
 </dependency>

Read zip from byte[] bytes example:

try (ZipArchiveInputStream zis = new ZipArchiveInputStream(
         new ByteArrayInputStream(bytes), "UTF8", false, true)) {
    ZipArchiveEntry ze;
    while ((ze = zis.getNextZipEntry()) != null) {
        log.info(ze.getName());
    }
}
查看更多
Luminary・发光体
4楼-- · 2020-07-10 12:38

Yes this is absolutely possible!

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.

And the ZipOutputStream can be sent anywhere, as its constructor just takes an OutputStream so could be e.g. your HTTP response.

查看更多
\"骚年 ilove
5楼-- · 2020-07-10 12:39

Input: D:/in.xml

Output: D:/final.zip (having 2 files 001zip.txt,002zip.txt)

Code:

package com.stackoverflow.filezip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class fileZip {

public static void main(String[] args) {

    try {
InputStream in = new FileInputStream("D:/in.xml");
OutputStream out=   new FileOutputStream("D:/final.zip");
ZipOutputStream zs = new ZipOutputStream(out);

            ZipEntry e1 = new ZipEntry("001zip.txt");
            ZipEntry e2 = new ZipEntry("002zip.txt");
            zs.putNextEntry(e1);
            zs.write("test content in file1".getBytes());
            zs.putNextEntry(e2);
            zs.write("test content in file2".getBytes());

            zs.close();
       }
       catch (Exception e) {
            e.printStackTrace();
                           }
                                       }
                       }
查看更多
登录 后发表回答