在java中的内存文件zip中

Kev*_*dra 2 java perl http

我试图从URL读取多个文件(可以是任何格式,即pdf,txt,tiff等)并使用它们进行压缩ZipOutputStream.我的代码看起来像这样:

    // 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);
Run Code Online (Sandbox Code Playgroud)

然后我将此内容"fileContent"传递给我的perl前端应用程序.

我使用perl代码下载此压缩文件:

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

但它提供的zip文件已损坏.我认为数据转换出了问题.

我很感激任何帮助.

Rog*_*sjö 5

您的问题是您可以将zip字节输出到字符串中.此字符串不能再用于再现zip内容.您需要使用原始字节或将字节编码为可以表示为字符串的内容,例如base64编码.