How to create compressed Zip archive using ZipOutputStream so that method getSize() of ZipEntry returns correct size?

后端 未结 2 2041
执念已碎
执念已碎 2021-02-14 19:23

Consider the code example that put a single file test_file.pdf into zip archive test.zip and then read this archive:

import java.io.*;
         


        
2条回答
  •  暖寄归人
    2021-02-14 19:41

    A simple and elegant workaround is to write the ZipEntry to a temporary ZipOutputStream first. This is what the updateEntry method of the following code does. When the method has been called, the ZipEntry knows the size, compressed size and CRC, without having to calculate them explicitly. When it is written to the target ZipOutputStream, it will correctly write the values.

    Original answer:


    dirty but fast

    public static void main(String[] args) throws IOException 
    {
        FileInputStream fis = new FileInputStream( "source.txt" );
        FileOutputStream fos = new FileOutputStream( "result.zip" );
        ZipOutputStream zos = new ZipOutputStream( fos );
    
        byte[] buf = new byte[fis.available()];
        fis.read(buf);
        ZipEntry e = new ZipEntry( "source.txt" );
    
        updateEntry(e, buf);
    
        zos.putNextEntry(e);
        zos.write(buf);
        zos.closeEntry();
    
        zos.close();
    }
    
    private static void updateEntry(ZipEntry entry, byte[] buffer) throws IOException
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream( bos );
        zos.putNextEntry(entry);
        zos.write(buffer);
        zos.closeEntry();
        zos.close();
        bos.close();
    }
    

提交回复
热议问题