java - java中的内存文件zip

标签 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);

然后我将此内容“fileContent”传递到我的 Perl 前端应用程序。

我正在使用 Perl 代码下载这个压缩文件:

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

但是它提供的 zip 文件已损坏。我认为数据翻译出了问题。

如果有任何帮助,我将不胜感激。

最佳答案

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

关于java - java中的内存文件zip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11122179/

相关文章:

node.js - 基于 Promise 的 Node http 框架?

c - 如何用c语言实现gmail的Oauth2.0

java - "Can' t find symbol“java.math.BigInteger 类中的错误

java - Spring Jdbctemplate 一对多数据检索

java - 如何覆盖 LWJGL 中的按键

c# - 如何从 token 创建 PlusService 的实例

Perl 搜索包含在数组中的字符串

perl - 为什么这个使用 tcpreplay 的脚本不等待用户输入?

linux - 解析输出并计算字符串出现的次数

security - session 攻击,新的攻击品种是什么?