博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How do I create a zip file?(转)
阅读量:6934 次
发布时间:2019-06-27

本文共 6821 字,大约阅读时间需要 22 分钟。

 

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

 

转载地址:http://migjl.baihongyu.com/

你可能感兴趣的文章
CSDN开源夏令营 百度数据可视化实践 ECharts(8)
查看>>
poj 1284 Primitive Roots(原根+欧拉函数)
查看>>
OpenJudge百炼习题解答(C++)--题4010:2011
查看>>
Oracle PL/SQL语句基础学习笔记(上)
查看>>
MVC,MVP 和 MVVM 的图示
查看>>
正則表達式常见例题
查看>>
STM32 使用 FreeRTOS过程记录
查看>>
ASP.NET Core身份认证服务框架IdentityServer4(2)-整体介绍
查看>>
P1064 金明的预算方案
查看>>
在 Spring 4.3.9下升级 Velocity 1.7.x to Velocity 2.0.x 出现的问题
查看>>
Python排序dict之list数组
查看>>
OKR
查看>>
cmake 常用变量和常用环境变量查表手册
查看>>
H极大值—lhMorpHMax
查看>>
asp.net创建文件夹出错的解决方案[转]
查看>>
[php] stop the NetBeans to scan the files automaticly
查看>>
都老了
查看>>
RFM模型分析与客户细分
查看>>
user-select介绍
查看>>
src源代码生成html格式文档
查看>>