How do I create a zip file?(转)

本文提供了一个完整的Java代码片段,演示如何使用ZipOutputStream和ZipEntry类创建ZIP文件,包含指定目录下所有文件。该ZIP文件为标准格式,可被广泛使用的压缩软件打开。代码中解释了创建ZIP文件的关键步骤,包括打开输出流、创建ZIP输出流、创建ZIP条目、写入文件数据等,并讨论了缓冲区大小的选择。同时,文章还详细说明了如何设置ZIP条目的名称、大小、最后修改时间和CRC32值。

 

Creating a zip file is a task that can easily be accomplished by using the classes ZipOutputStream and ZipEntry in the java.util.zip package.

First of all, I'm going to present to you a complete code snippet that will create a zip file containing all the files of a specified directory. The resulting zip file has the same name as the given directory, with the .zip extention. The archive will be a valid zip file which can be opened with almost all standard zip archivers, such as WinZip.

Here is the complete code - read on, after the code I'll explain some parts in detail.

import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import java.util.zip.CRC32;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    public class CreateZipFile
    {
    
        private final int BUFFER_SIZE = 4096;
        
        public void addFileToZip(ZipOutputStream zos, File file)
        {
            byte [] data = new byte[BUFFER_SIZE]; 
            int len; 
            
            FileInputStream fis = null;
            try
            {
                ZipEntry entry = new ZipEntry(file.getName()); 
                entry.setSize(file.length()); 
                entry.setTime(file.lastModified()); 
                
                zos.putNextEntry(entry); 
                fis = new FileInputStream(file); 
                
                CRC32 crc32 = new CRC32(); 
                while ((len = fis.read(data)) > -1)
                { 
                    zos.write(data, 0, len); 
                    crc32.update(data, 0, len); 
                } 
                entry.setCrc(crc32.getValue());
                
                zos.closeEntry(); 
            }
            catch (IOException ioe)
            {
                ioe.printStackTrace();
            }
            finally
            {
                try
                {
                    if (fis != null)
                    {
                        fis.close(); 
                    }
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
        
        public void createZipFile(String directory)
        {
            File dir = new File(directory);
            if (dir.isDirectory())
            {
                File [] files = dir.listFiles();
                if (files != null)
                {
                    File zip = new File(dir.getName() + ".zip");
                    
                    FileOutputStream fos = null;
                    ZipOutputStream  zos = null;

                    try
                    {
                        fos = new FileOutputStream(zip); 
                        zos = new ZipOutputStream(fos); 
                        zos.setMethod(ZipOutputStream.DEFLATED); 
                        
                        for (int i = 0; i < files.length; i++)
                        {
                            if (files[i].isFile())
                            {
                                System.out.println("Zipping " + files[i].getName());
                                addFileToZip(zos, files[i]);
                            }
                        }
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        fnfe.printStackTrace();
                    }
                    finally
                    {
                        if (zos != null)
                        {
                            try
                            {
                                zos.close();
                            }
                            catch (IOException ioe)
                            {
                                ioe.printStackTrace();
                            }
                        }
                        if (fos != null)
                        {
                            try
                            {
                                fos.close();
                            }
                            catch (IOException ioe)
                            {
                                ioe.printStackTrace();
                            }
                        }
                    }
                }            
            }
            else
            {
                System.out.println(dir.getName() + " is not a directory");
            }
        }
        
        public static void main(String [] args)
        {
            if (args.length == 1)
            {
                CreateZipFile czf = new CreateZipFile();
                czf.createZipFile(args[0]);
            }
            else
            {
                System.out.println("usage: java CreateZipFile directory");
            }
        }
    
    }

 

The steps that you need to take in order to create a zip file are the following:

  1. open an OutputStream (for example a FileOutputStream)
  2. open a ZipOutputStream
  3. prepare a ZipEntry for each file you would like to add to the zip
  4. write the file data to the prepared ZipEntry
  5. close the ZipEntry
  6. repeat steps 3 through 5 for each additional file you'd like to add
  7. close the ZipOutputStream
  8. close the OutputStream

Let's have a look at steps 3 through 5, which need to be repeated for each file.

    ZipEntry entry = new ZipEntry(file.getName()); 
    entry.setSize(file.length()); 
    entry.setTime(file.lastModified()); 

A new ZipEntry is created, the name, size and time of the zipped entity are set. Please note that the CRC32 value is not set at this moment. We'll see later on why this is.

    zos.putNextEntry(entry); 
    fis = new FileInputStream(file); 

The entry has now been added to a ZipOutputStream which was passed to this method as an argument. An InputStream is opened to read the contents of the file we would like to zip.

    CRC32 crc32 = new CRC32(); 
    while ((len = fis.read(data)) > -1)
    { 
        zos.write(data, 0, len); 
        crc32.update(data, 0, len); 
    } 
    entry.setCrc(crc32.getValue()); 

We did not set the CRC32 value when we created the ZipEntry. Now we can make up for this: while we add the data to the ZipOutputStream, we calculate the CRC32 value. The benefit of this approach is that we only need to read the contents of the file once, whereas we would have had to read the file twice should we have wanted to do this up front.

    zos.closeEntry(); 

After all this, we only need to close the ZipEntry we added to the ZipOutputStream. We are now ready to add another entry, or we can close the zip file at this point.

Perhaps a final note on the BUFFER_SIZE I used in this example. It is possible to use a smaller or larger buffer size in the example, but please note that setting a size that's too big or too small will hurt performance.

http://jcsnippets.atspace.com/java/input-output/create-zip-file.html

 

转载于:https://www.cnblogs.com/softidea/p/4273074.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值