简体   繁体   English

无法使用Java压缩多个文件

[英]Unable to zip multiple files using Java

Getting data onto inputStream object from web url 从Web URL将数据获取到inputStream对象上

inputStream = AWSFileUtil.getInputStream(
                    AWSConnectionUtil.getS3Object(null),
                    "cdn.generalsentiment.com", filePath);

If they are mutliple files then i want to zip them and sent the filetype as "zip" to struts.xml which does the download. 如果它们是多文件,那么我想将它们压缩并以“ zip”格式发送文件到进行下载的struts.xml。

actually am converting the inputstream into byteArrayInputStream 实际上是将输入流转换为byteArrayInputStream

ByteArrayInputStream byteArrayInputStream = new    
ByteArrayInputStream(inputStream.toString().getBytes());
            while (byteArrayInputStream.read(inputStream.toString().getBytes()) > 0) {
                zipOutputStream.write(inputStream.toString().getBytes());
            }

and then 接着

 zipOutputStream.close();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        fileInputStream = new FileInputStream(file);
        while (fileInputStream.read(buffer) > 0) {
            byteArrayOutputStream.write(buffer);
        }
        byteArrayOutputStream.close();
        inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        reportName = "GS_MediaValue_Reports.zip";
        fileType = "zip";
    } 

    return fileType;

But the downloaded zip when extracted gives corrupt files. 但是,解压缩时下载的zip会损坏文件。 Please suggest me a solution for this issue. 请为我建议这个问题的解决方案。

The short answer is that it's not how ZipOutputStream works. 简短的答案是,它不是ZipOutputStream工作方式。 Since it was designed to store multiple files, along with their file names, directory structures and so on, you need to tell the stream about that explicitly. 由于它被设计为存储多个文件以及它们的文件名,目录结构等,因此您需要显式地告诉流。

Furthermore, converting a stream to a string is a bad idea in general, plus it's slow, especially when you're doing it in a loop. 此外,将流转换为字符串通常不是一个好主意,而且速度很慢,尤其是在循环执行时。

So your solution will be something like: 所以您的解决方案将是这样的:

ZipEntry entry = new ZipEntry( fileName ); // You have to give each entry a different filename
zipOutputStream.putNextEntry( entry );
byte buffer[] = new byte[ 1024 ]; // 1024 is the buffer size here, but it could be anything really
int count;
while( (count = inputStream.read( buffer, 0, 1024 ) ) != -1 ) {
    zipOutputStream.write( buffer, 0, count );
}

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

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