简体   繁体   English

在Java中的内存文件zip中

[英]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 . 我试图从URL读取多个文件(可以是pdf,txt,tiff等任何格式),并使用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. 然后,我将此内容“ fileContent”传递给我的perl前端应用程序。

And I m using perl code to download this zipped file: 我正在使用Perl代码下载此压缩文件:

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. 但是它提供的zip文件已损坏。 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. 您的问题是您可以将zip字节输出为字符串。 This string can not be used to reproduce the zip content again. 该字符串不能再次用于再现zip内容。 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. 您需要使用原始字节或将字节编码为可以表示为字符串的内容,例如base64编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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