簡體   English   中英

設置僅流式傳輸的 zip 文件的文件名

[英]Set filename of an only streamed zip file

我目前正在創建一個 zip 文件並用各種 json 文件和圖像填充它。 所有這些都應該只在 memory 中運行,而不是在硬盤上。 因此,到目前為止,我有以下構造:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zip = null;
String FILE_NAME = "file.zip";

try {
   zip = new ZipOutputStream(baos);
   //now the critical part where the name of the file should be set
   ZipEntry entry = new ZipEntry(FILE_NAME);
   zip.putNextEntry(entry);
   byte[] data = FILE_NAME.getBytes();
   zip.write(data, 0, data.length);
   zip.closeEntry();
   //end of critical part and filling the rest of the zip
   //...
   //
}finally{
   IOUtils.closeQuietly(zip);
   byte[] byteFile = baos.toByteArray();
   IOUtils.closeQuietly(baos);}

問題是壓縮文件名為file.zip,但還包含一個文件.zip 本身。 如何從 ZipOutputStream 中命名我的 Zip 文件而不打包到同名的這個文件中? 不幸的是,我只在這里找到了這個解決方案。

public byte[] zipBytesFile(List<byte[]> files) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    int i = 0;
    for (byte[] file : files) {
        ZipEntry entry = new ZipEntry(++i + ".pdf");
        entry.setSize(file.length);
        zos.putNextEntry(entry);
        zos.write(file);
    }

    zos.closeEntry();
    zos.close();
    return baos.toByteArray();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM