How do I create a zip file?(转)
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:
- open an OutputStream (for example a FileOutputStream)
- open a ZipOutputStream
- prepare a ZipEntry for each file you would like to add to the zip
- write the file data to the prepared ZipEntry
- close the ZipEntry
- repeat steps 3 through 5 for each additional file you'd like to add
- close the ZipOutputStream
- 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?(转)的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- zip file 压缩文件
有时候我们希望 upload 文件后自动压缩, 可以节省空间. 可以使用微软提供的压缩代码 Install-Package System.IO.Compression.ZipFile -Version ...
- ionic build Android错误记录 error in opening zip file
0.写在前头 运行 :cordova requirements Requirements check results for android: Java JDK: installed 1.8.0 An ...
- 记一个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 ...
- 解决: 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 ...
- linux下解压大于4G文件提示error: Zip file too big错误的解决办法
error: Zip file too big (greater than 4294959102 bytes)错误解决办法.zip文件夹大于4GB,在centos下无法正常unzip,需要使用第三方工 ...
- maven install 读取jar包时出错;error in opening zip file
错误信息: [INFO] ------------------------------------------------------------------------ [ERROR] Failed ...
随机推荐
- jsp_javabean
什么是javabean? 遵循一定的设计原则的任何java类都可以是javabean组件 1.可序列化 implements serializable 2.无参数的构造方法 3.私有属性 通过公有方法 ...
- 关于 Swift
摘自:http://numbbbbb.gitbooks.io/-the-swift-programming-language-/chapter1/01_swift.html Swift 是一种新的编程 ...
- 使用VS+VisualGDB编译Linux版本RCF(相当于Linux也有COM版本了)
阅读目录 通过向导配置项目 配置目录结构 修改项目配置 添加RCF源代码 完成配置并进行编译 添加测试程序 添加测试代码——通过TCP进行通信 运行测试程序并查看测试结果 VisualGDB生成的所有 ...
- asp.net 生成、解析条形码和二维码
原文 asp.net 生成.解析条形码和二维码 一.条形码 一维码,俗称条形码,广泛的用于电子工业等行业.比如我们常见的书籍背面就会有条形码,通过扫描枪等设备扫描就可以获得书籍的ISBN(Intern ...
- 我的Android进阶之旅------>HTTP 返回状态值详解
(本文转载于:http://blog.csdn.net/ithomer/article/details/10240351) 当用户点击或搜索引擎向网站服务器发出浏览请求时,服务器将返回Http Hea ...
- C#:总结页面传值几种方法
小知识点: 1. W7自带 .NetFrameWork 3.5, 兼容模式为 高版本号兼容低版本号: 2. WF和WPF都是基于XAML的,可是两者的用途不同. WF是一种开发框架,将工作流嵌入在. ...
- Makefile学习(二)[第二版]
复杂实例 #演示样例1:在上一个演示样例的基础上再添加一个可运行文件03test[改动之处已标红] .PHONY: clean all CC = gcc CFLAGS = -Wall -g BIN = ...
- Swift实现糗事百科Demo(实战项目)
在这里,你将会学习到解析JSON数据,网络请求功能,动态调整cell内容等功能!!! 最终的结果 是这样的,项目相对简单,很适合入门!下面让我们一起开始教程之旅吧! 1.先看下项目工程结构: 第一步: ...
- 手把手教你安装QT集成开发环境(操作系统为ubuntu10.04)
在安装QT集成开发工具包之前需要先安装build-essential和libncurses5-dev这两个开发工具和库,libncurses5-dev库是一个在Linux/Unix下广泛应用的图形函数 ...
- java 一个函数EnumMap返回多个值
java 一个函数如何返回多个值 在开发过程中,经常会有这种情况,就是一个函数需要返回多个值,这是一个问题!! 网上这个问题的解决方法: 1.使用map返回值:这个方法问题是,你并不知道如何返回值 ...