【问题标题】:Saving ZipOutputStream to zip file with Java使用 Java 将 ZipOutputStream 保存为 zip 文件
【发布时间】:2015-02-20 12:49:52
【问题描述】:

我必须在内存中创建 ZIP 存档 但现在,我需要将它保存在磁盘中的真实 .zip 文件中。怎么做? 伪代码:

public byte[] crtZipByteArray(ByteArrayInputStream data,ZipEntry entry) throws IOException{
     ByteArrayOutputStream zipout = new ByteArrayOutputStream(); 
    ZipOutputStream zos = new ZipOutputStream(zipout);
    byte[] buffer = new byte[1024];
    int len;
    zos.putNextEntry(entry);
    while ((len = data.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }
    zos.closeEntry();

    zos.close();
    data.close();
    return zipout.toByteArray();
}

【问题讨论】:

标签: java memory zip zipoutputstream


【解决方案1】:

ByteArrayOutputStream zipout 替换为FileOutputStream zipout

如果您仍然需要返回字节数组作为方法结果,请使用 apache commons TeeOutputStream 复制两个流的输出。

public byte[] crtZipByteArray(ByteArrayInputStream data,ZipEntry entry) throws IOException{
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); 
        OutputStream fileOut = new FileOutputStream("filename.zip");
        OutputStream teeOut = new TeeOutputStream(byteArrayOut, fileOut);
        ZipOutputStream zos = new ZipOutputStream(teeOut);
.....
}

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    相关资源
    最近更新 更多