我正在尝试从 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/