简体   繁体   中英

in memory file zip in java

I am trying to read multiple files (can be of any format ie pdf, txt, tiff etc) from URLs and zipping them using ZipOutputStream . My code looks like this:

    // using in-memory file read
    // then zipping all these files in-memory
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    .....

    URL url = new URL(downloadUrl); // can be multiple URLs

    ByteArrayOutputStream bais = new ByteArrayOutputStream();
    InputStream is = url.openStream();
    byte[] byteChunk = new byte[4096];
    int n;

    while ( (n = is.read(byteChunk)) > 0 )
    {
        bais.write(byteChunk, 0, n);
    }

    byte[] fileBytes = bais.toByteArray();

    ZipEntry entry = new ZipEntry(fileName);
    entry.setSize(fileBytes.length);

    zos.putNextEntry(entry);
    zos.write(fileBytes);
    zos.closeEntry();

    // close the url input stream 
    is.close();

    // close the zip output stream
zos.close();


    // read the byte array from ByteArrayOutputStream
    byte[] zipFileBytes = baos.toByteArray();

    String fileContent = new String(zipFileBytes);

I am then passing this content "fileContent" to my perl frontend application.

And I m using perl code to download this zipped file:

WPHTTPResponse::setHeader( 'Content-disposition', 'attachment; filename="test.zip"' );
WPHTTPResponse::setHeader( 'Content-type', 'application/zip');
print $result; // string coming from java application

But the zip file it is giving is corrupted. I think something in going wrong with the data translation.

I'd appreciate any help.

Your problem is thinking that you can output your zip bytes into a string. This string can not be used to reproduce the zip content again. You need to either use the raw bytes or encode the bytes into something that can be represented as a string, such as base64 encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM