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

How do I create a zip file?(转)的更多相关文章

  1. How to create a zip file in NetSuite SuiteScript 2.0 如何在现有SuiteScript中创建和下载ZIP压缩文档

    Background We all knows that: NetSuite filecabinet provided a feature to download a folder to a zip ...

  2. How do I create zip file in Servlet for download?

    原文链接:https://kodejava.org/how-do-i-create-zip-file-in-servlet-for-download/ The example below is a s ...

  3. Java ZIP File Example---refernce

    In this tutorial we are going to see how to ZIP a file in Java. ZIP is an archive file format that e ...

  4. zip file 压缩文件

    有时候我们希望 upload 文件后自动压缩, 可以节省空间. 可以使用微软提供的压缩代码 Install-Package System.IO.Compression.ZipFile -Version ...

  5. ionic build Android错误记录 error in opening zip file

    0.写在前头 运行 :cordova requirements Requirements check results for android: Java JDK: installed 1.8.0 An ...

  6. 记一个mvn奇怪错误: Archive for required library: 'D:/mvn/repos/junit/junit/3.8.1/junit-3.8.1.jar' in project 'xxx' cannot be read or is not a valid ZIP file

    我的maven 项目有一个红色感叹号, 而且Problems 存在 errors : Description Resource Path Location Type Archive for requi ...

  7. 解决: org.iq80.leveldb.DBException: IO error: C:\data\trie\000945.sst: Could not create random access file.

    以太坊MPT树的持久化层是采用了leveldb数据库,然而在抽取MPT树代码运行过程中,进行get和write操作时却发生了错误: Caused by: org.fusesource.leveldbj ...

  8. linux下解压大于4G文件提示error: Zip file too big错误的解决办法

    error: Zip file too big (greater than 4294959102 bytes)错误解决办法.zip文件夹大于4GB,在centos下无法正常unzip,需要使用第三方工 ...

  9. maven install 读取jar包时出错;error in opening zip file

    错误信息: [INFO] ------------------------------------------------------------------------ [ERROR] Failed ...

随机推荐

  1. android:android:background="#00000000",透明效果

    ImageButton中设置 android:background="#00000000",可以达到透明效果 具体的源码 管理-->文件中的 viewpager0829.ra ...

  2. 输入输出函数 I/O函数之perror()

    perror()函数的函数原型 void perror(char const *message); 它会将message信息输出出来,后面再加上错误原因字符串. 下面是来自百度百科的实例: #incl ...

  3. Activity的绘制流程简单分析(基于android 4.0源码进行分析)

    要明白这个流程,我们还得从第一部开始,大家都知道 在activity里面 setcontentview 调用结束以后 就可以看到程序加载好我们的布局文件了,从而让我们在手机上看到这个画面. 那么我们来 ...

  4. perl 当前包会覆盖父类的同名方法

    12.5.2 访问被覆盖的方法: 当一个类定义一个方法,那么该子过程覆盖任意基类中同名的方法. [root@wx03 test]# cat Horse.pm package Horse; our @I ...

  5. 公司简介 - CCDI悉地国际-工程实践专业服务的引领者

    公司简介 - CCDI悉地国际-工程实践专业服务的引领者 关于悉地国际         CCDI悉地国际(以下简称"CCDI")创立于1994年,是在城市建设和开发领域从事综合专业 ...

  6. iOS &quot;The sandbox is not in sync with the Podfile.lock&quot;解决方式

    更新Cocoapod之后出现故障: diff: /../Podfile.lock: No such file or directory diff: Manifest.lock: No such fil ...

  7. EasyUI - DataGrid 组建 - [ 排序功能 ]

    效果: 红框的字段看,为设置了,列排序,向后台Post数据sort/order. 原理:向后台POST数据,sort/post数据. html代码: <table id="tab&qu ...

  8. (摘录)ASP.NET提供文件下载函数(支持大文件、续传、速度限制、资源占用小)

    // 输出硬盘文件,提供下载 // 输入参数 _Request: Page.Request对象, _Response: Page.Response对象, _fileName: 下载文件名, _full ...

  9. Windows Azure使用VS 2010的云应用开发过程

    原文 Windows Azure使用VS 2010的云应用开发过程 作为技术人员,如果在2010还不知道云计算,那么你已经“OUT”了:作为Visual Studio平台的使用者,如果你不知道VS 2 ...

  10. 【OpenCV】漫水填充

    漫水填充:也就是用一定颜色填充联通区域,通过设置可连通像素的上下限以及连通方式来达到不同的填充效果;漫水填充经常被用来标记或分离图像的一部分以便对其进行进一步处理或分析,也可以用来从输入图像获取掩码区 ...