---
title: "利用Java实现压缩与解压缩（zip、gzip）支持中文路径"
author: "rayn115"
date: "2011-10-19T22:21:52Z"
tags: []
categories: ["编程语言"]
slug: "java-zip-gzip"
draft: false
lastmod: "2011-10-19T22:21:52Z"
id: 1202303
url: "https://rayn115.iteye.com/blog/1202303"
---

zip扮演着归档和压缩两个角色；gzip并不将文件归档，仅只是对单个文件进行压缩，所以，在UNIX平台上，命令tar通常用来创建一个档案文件，然后命令gzip来将档案文件压缩。

Java I/O类库还收录了一些能读写压缩格式流的类。要想提供压缩功能，只要把它们包在已有的I/O类的外面就行了。这些类不是Reader和Writer，而是InputStream和OutStreamput的子类。这是因为压缩算法是针对byte而不是字符的。

相关类与接口：  
**Checksum** 接口：被类Adler32和CRC32实现的接口  
**Adler32** ：使用Alder32算法来计算Checksum数目  
**CRC32** ：使用CRC32算法来计算Checksum数目

**CheckedInputStream** ：InputStream派生类，可得到输入流的校验和Checksum，用于校验数据的完整性  
**CheckedOutputStream** ：OutputStream派生类，可得到输出流的校验和Checksum， 用于校验数据的完整性

**DeflaterOutputStream** ：压缩类的基类。  
**ZipOutputStream** ：DeflaterOutputStream的一个子类，把数据压缩成Zip文件格式。  
**GZIPOutputStream** ：DeflaterOutputStream的一个子类，把数据压缩成GZip文件格式

**InflaterInputStream** ：解压缩类的基类  
**ZipInputStream** ：InflaterInputStream的一个子类，能解压缩Zip格式的数据  
**GZIPInputStream** ：InflaterInputStream的一个子类，能解压缩Zip格式的数据

**ZipEntry** 类：表示 ZIP 文件条目  
**ZipFile** 类：此类用于从 ZIP 文件读取条目

## 用GZIP进行对单个文件压缩

GZIP的接口比较简单，因此如果你只需对一个流进行压缩的话，可以使用它。当然它可以压缩字符流，与可以压缩字节流，下面是一个对GBK编码格式的文本文件进行压缩的。  
压缩类的用法非常简单；只要用GZIPOutputStream 或ZipOutputStream把输出流包起来，再用GZIPInputStream 或ZipInputStream把输入流包起来就行了。剩下的都是些普通的I/O操作。

Java代码  [![收藏代码](http://jiangzhengjun.iteye.com/images/icon_star.png)]()

01. import  java.io.BufferedOutputStream;
02. import  java.io.BufferedReader;
03. import  java.io.FileInputStream;
04. import  java.io.FileOutputStream;
05. import  java.io.IOException;
06. import  java.io.InputStreamReader;
07. import  java.util.zip.GZIPInputStream;
08. import  java.util.zip.GZIPOutputStream;
09. public   class  GZIPcompress {
10. public   static   void  main(String\[] args)  throws  IOException {
11. //做准备压缩一个字符文件，注，这里的字符文件要是GBK编码方式的
12. BufferedReader in = new  BufferedReader( new  InputStreamReader( new  FileInputStream(
13. "e:/tmp/source.txt" ),  "GBK" ));
14. //使用GZIPOutputStream包装OutputStream流，使其具体压缩特性，最后会生成test.txt.gz压缩包
15. //并且里面有一个名为test.txt的文件
16. BufferedOutputStream out = new  BufferedOutputStream( new  GZIPOutputStream(
17. new  FileOutputStream( "test.txt.gz" )));
18. System.out.println("开始写压缩文件..." );
19. int  c;
20. while  ((c = in.read()) != - 1 ) {
21. /*
22. * 注，这里是压缩一个字符文件，前面是以字符流来读的，不能直接存入c，因为c已是Unicode
23. * 码，这样会丢掉信息的（当然本身编码格式就不对），所以这里要以GBK来解后再存入。
24. \*/
25. out.write(String.valueOf((char ) c).getBytes( "GBK" ));
26. }
27. in.close();
28. out.close();
29. System.out.println("开始读压缩文件..." );
30. //使用GZIPInputStream包装InputStream流，使其具有解压特性
31. BufferedReader in2 = new  BufferedReader( new  InputStreamReader(
32. new  GZIPInputStream( new  FileInputStream( "test.txt.gz" )),  "GBK" ));
33. String s;
34. //读取压缩文件里的内容
35. while  ((s = in2.readLine()) !=  null ) {
36. System.out.println(s);
37. }
38. in2.close();
39. }
40. }

## 使用Zip进行多个文件压缩

Java对Zip格式类库支持得比较全面，得用它可以把多个文件压缩成一个压缩包。这个类库使用的是标准Zip格式，所以能与很多的压缩工具兼容。

ZipOutputStream类有设置压缩方法以及在压缩方式下使用的压缩级别，zipOutputStream.setMethod(int method)设置用于条目的默认压缩方法。只要没有为单个 ZIP 文件条目指定压缩方法，就使用ZipOutputStream所设置的压缩方法来存储，默认值为 ZipOutputStream.DEFLATED（表示进行压缩存储），还可以设置成STORED（表示仅打包归档存储）。 ZipOutputStream在设置了压缩方法为DEFLATED后，我们还可以进一步使用setLevel(int level)方法来设置压缩级别，压缩级别值为0-9共10个级别(值越大，表示压缩越利害)，默认为 Deflater.DEFAULT\_COMPRESSION=-1。当然我们也可以通过条目ZipEntry的setMethod方法为单个条件设置压缩 方法。

类ZipEntry描述了存储在ZIP文件中的压缩文件。类中包含有多种方法可以用来设置和获得ZIP条目的信息。类ZipEntry是被 ZipFile\[zipFile.getInputStream(ZipEntry entry)]和ZipInputStream使用来读取ZIP文件，ZipOutputStream来写入ZIP文件的。有以下这些有用的方 法：getName()返回条目名称、isDirectory()如果为目录条目，则返回 true（目录条目定义为其名称以 '/' 结尾的条目）、setMethod(int method) 设置条目的压缩方法，可以为 ZipOutputStream.STORED 或 ZipOutputStream .DEFLATED。

 

下面实例我们使用了apache的zip工具包（所在包为**ant.jar** ），因为java类型自带的不支持中文路径，不过两者使用的方式是一样的，只是apache压缩工具多了设置编码方式的接口，其他基本上是一样的。另外， 如果使用org.apache.tools.zip.ZipOutputStream来压缩的话，我们只能使用 org.apache.tools.zip.ZipEntry来解压，而不能使用java.util.zip.ZipInputStream来解压读取 了，当然apache并未提供ZipInputStream类。

 

Java代码  [![收藏代码](http://jiangzhengjun.iteye.com/images/icon_star.png)]()

001. import  java.io.BufferedInputStream;
002. import  java.io.BufferedOutputStream;
003. import  java.io.File;
004. import  java.io.FileInputStream;
005. import  java.io.FileNotFoundException;
006. import  java.io.FileOutputStream;
007. import  java.io.IOException;
008. import  java.util.Enumeration;
009. import  java.util.zip.CRC32;
010. import  java.util.zip.CheckedInputStream;
011. import  java.util.zip.CheckedOutputStream;
012. import  java.util.zip.Deflater;
013. import  java.util.zip.ZipException;
014. import  java.util.zip.ZipInputStream;
015. import  org.apache.tools.zip.ZipEntry;
016. import  org.apache.tools.zip.ZipFile;
017. import  org.apache.tools.zip.ZipOutputStream;
018. /\**
019. \*
020. * 提供对单个文件与目录的压缩，并支持是否需要创建压缩源目录、中文路径
021. \*
022. * @author jzj
023. \*/
024. public   class  ZipCompress {
025. private   static   boolean  isCreateSrcDir =  true ; //是否创建源目录
026. /\**
027. * @param args
028. * @throws IOException
029. \*/
030. public   static   void  main(String\[] args)  throws  IOException {
031. String src = "m:/新建文本文档.txt" ; //指定压缩源，可以是目录或文件
032. String decompressDir = "e:/tmp/decompress" ; //解压路径
033. String archive = "e:/tmp/test.zip" ; //压缩包路径
034. String comment = "Java Zip 测试." ; //压缩包注释
035. //----压缩文件或目录
036. writeByApacheZipOutputStream(src, archive, comment);
037. /*
038. * 读压缩文件，注释掉，因为使用的是apache的压缩类，所以使用java类库中
039. * 解压类时出错，这里不能运行
040. \*/
041. //readByZipInputStream();
042. //----使用apace ZipFile读取压缩文件
043. readByApacheZipFile(archive, decompressDir);
044. }
045. public   static   void  writeByApacheZipOutputStream(String src, String archive,
046. String comment) throws  FileNotFoundException, IOException {
047. //----压缩文件：
048. FileOutputStream f = new  FileOutputStream(archive);
049. //使用指定校验和创建输出流
050. CheckedOutputStream csum = new  CheckedOutputStream(f,  new  CRC32());
051. ZipOutputStream zos = new  ZipOutputStream(csum);
052. //支持中文
053. zos.setEncoding("GBK" );
054. BufferedOutputStream out = new  BufferedOutputStream(zos);
055. //设置压缩包注释
056. zos.setComment(comment);
057. //启用压缩
058. zos.setMethod(ZipOutputStream.DEFLATED);
059. //压缩级别为最强压缩，但时间要花得多一点
060. zos.setLevel(Deflater.BEST\_COMPRESSION);
061. File srcFile = new  File(src);
062. if  (!srcFile.exists() || (srcFile.isDirectory() && srcFile.list().length ==  0 )) {
063. throw   new  FileNotFoundException(
064. "File must exist and  ZIP file must have at least one entry." );
065. }
066. //获取压缩源所在父目录
067. src = src.replaceAll("\\\\\\\\", " /");
068. String prefixDir = null ;
069. if  (srcFile.isFile()) {
070. prefixDir = src.substring(0 , src.lastIndexOf( "/" ) +  1 );
071. } else  {
072. prefixDir = (src.replaceAll("/$" ,  "" ) +  "/" );
073. }
074. //如果不是根目录
075. if  (prefixDir.indexOf( "/" ) != (prefixDir.length() -  1 ) && isCreateSrcDir) {
076. prefixDir = prefixDir.replaceAll("\[^/]+/$" ,  "" );
077. }
078. //开始压缩
079. writeRecursive(zos, out, srcFile, prefixDir);
080. out.close();
081. // 注：校验和要在流关闭后才准备，一定要放在流被关闭后使用
082. System.out.println("Checksum: "  + csum.getChecksum().getValue());
083. BufferedInputStream bi;
084. }
085. /\**
086. * 使用 org.apache.tools.zip.ZipFile 解压文件，它与 java 类库中的
087. * java.util.zip.ZipFile 使用方式是一新的，只不过多了设置编码方式的
088. * 接口。
089. \*
090. * 注，apache 没有提供 ZipInputStream 类，所以只能使用它提供的ZipFile
091. * 来读取压缩文件。
092. * @param archive 压缩包路径
093. * @param decompressDir 解压路径
094. * @throws IOException
095. * @throws FileNotFoundException
096. * @throws ZipException
097. \*/
098. public   static   void  readByApacheZipFile(String archive, String decompressDir)
099. throws  IOException, FileNotFoundException, ZipException {
100. BufferedInputStream bi;
101. ZipFile zf = new  ZipFile(archive,  "GBK" ); //支持中文
102. Enumeration e = zf.getEntries();
103. while  (e.hasMoreElements()) {
104. ZipEntry ze2 = (ZipEntry) e.nextElement();
105. String entryName = ze2.getName();
106. String path = decompressDir + "/"  + entryName;
107. if  (ze2.isDirectory()) {
108. System.out.println("正在创建解压目录 - "  + entryName);
109. File decompressDirFile = new  File(path);
110. if  (!decompressDirFile.exists()) {
111. decompressDirFile.mkdirs();
112. }
113. } else  {
114. System.out.println("正在创建解压文件 - "  + entryName);
115. String fileDir = path.substring(0 , path.lastIndexOf( "/" ));
116. File fileDirFile = new  File(fileDir);
117. if  (!fileDirFile.exists()) {
118. fileDirFile.mkdirs();
119. }
120. BufferedOutputStream bos = new  BufferedOutputStream( new  FileOutputStream(
121. decompressDir + "/"  + entryName));
122. bi = new  BufferedInputStream(zf.getInputStream(ze2));
123. byte \[] readContent =  new   byte \[ 1024 ];
124. int  readCount = bi.read(readContent);
125. while  (readCount != - 1 ) {
126. bos.write(readContent, 0 , readCount);
127. readCount = bi.read(readContent);
128. }
129. bos.close();
130. }
131. }
132. zf.close();
133. }
134. /\**
135. * 使用 java api 中的 ZipInputStream 类解压文件，但如果压缩时采用了
136. * org.apache.tools.zip.ZipOutputStream时，而不是 java 类库中的
137. * java.util.zip.ZipOutputStream时，该方法不能使用，原因就是编码方
138. * 式不一致导致，运行时会抛如下异常：
139. * java.lang.IllegalArgumentException
140. * at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:290)
141. \*
142. * 当然，如果压缩包使用的是java类库的java.util.zip.ZipOutputStream
143. * 压缩而成是不会有问题的，但它不支持中文
144. \*
145. * @param archive 压缩包路径
146. * @param decompressDir 解压路径
147. * @throws FileNotFoundException
148. * @throws IOException
149. \*/
150. public   static   void  readByZipInputStream(String archive, String decompressDir)
151. throws  FileNotFoundException, IOException {
152. BufferedInputStream bi;
153. //----解压文件(ZIP文件的解压缩实质上就是从输入流中读取数据):
154. System.out.println("开始读压缩文件" );
155. FileInputStream fi = new  FileInputStream(archive);
156. CheckedInputStream csumi = new  CheckedInputStream(fi,  new  CRC32());
157. ZipInputStream in2 = new  ZipInputStream(csumi);
158. bi = new  BufferedInputStream(in2);
159. java.util.zip.ZipEntry ze;//压缩文件条目
160. //遍历压缩包中的文件条目
161. while  ((ze = in2.getNextEntry()) !=  null ) {
162. String entryName = ze.getName();
163. if  (ze.isDirectory()) {
164. System.out.println("正在创建解压目录 - "  + entryName);
165. File decompressDirFile = new  File(decompressDir +  "/"  + entryName);
166. if  (!decompressDirFile.exists()) {
167. decompressDirFile.mkdirs();
168. }
169. } else  {
170. System.out.println("正在创建解压文件 - "  + entryName);
171. BufferedOutputStream bos = new  BufferedOutputStream( new  FileOutputStream(
172. decompressDir + "/"  + entryName));
173. byte \[] buffer =  new   byte \[ 1024 ];
174. int  readCount = bi.read(buffer);
175. while  (readCount != - 1 ) {
176. bos.write(buffer, 0 , readCount);
177. readCount = bi.read(buffer);
178. }
179. bos.close();
180. }
181. }
182. bi.close();
183. System.out.println("Checksum: "  + csumi.getChecksum().getValue());
184. }
185. /\**
186. * 递归压缩
187. \*
188. * 使用 org.apache.tools.zip.ZipOutputStream 类进行压缩，它的好处就是支持中文路径，
189. * 而Java类库中的 java.util.zip.ZipOutputStream 压缩中文文件名时压缩包会出现乱码。
190. * 使用 apache 中的这个类与 java 类库中的用法是一新的，只是能设置编码方式了。
191. \*
192. * @param zos
193. * @param bo
194. * @param srcFile
195. * @param prefixDir
196. * @throws IOException
197. * @throws FileNotFoundException
198. \*/
199. private   static   void  writeRecursive(ZipOutputStream zos, BufferedOutputStream bo,
200. File srcFile, String prefixDir) throws  IOException, FileNotFoundException {
201. ZipEntry zipEntry;
202. String filePath = srcFile.getAbsolutePath().replaceAll("\\\\\\\\", " /").replaceAll(
203. "//" ,  "/" );
204. if  (srcFile.isDirectory()) {
205. filePath = filePath.replaceAll("/$" ,  "" ) +  "/" ;
206. }
207. String entryName = filePath.replace(prefixDir, "" ).replaceAll( "/$" ,  "" );
208. if  (srcFile.isDirectory()) {
209. if  (! "" .equals(entryName)) {
210. System.out.println("正在创建目录 - "  + srcFile.getAbsolutePath()
211. + "  entryName="  + entryName);
212. //如果是目录，则需要在写目录后面加上 /
213. zipEntry = new  ZipEntry(entryName +  "/" );
214. zos.putNextEntry(zipEntry);
215. }
216. File srcFiles\[] = srcFile.listFiles();
217. for  ( int  i =  0 ; i &lt; srcFiles.length; i++) {
218. writeRecursive(zos, bo, srcFiles\[i], prefixDir);
219. }
220. } else  {
221. System.out.println("正在写文件 - "  + srcFile.getAbsolutePath() +  "  entryName="
222. + entryName);
223. BufferedInputStream bi = new  BufferedInputStream( new  FileInputStream(srcFile));
224. //开始写入新的ZIP文件条目并将流定位到条目数据的开始处
225. zipEntry = new  ZipEntry(entryName);
226. zos.putNextEntry(zipEntry);
227. byte \[] buffer =  new   byte \[ 1024 ];
228. int  readCount = bi.read(buffer);
229. while  (readCount != - 1 ) {
230. bo.write(buffer, 0 , readCount);
231. readCount = bi.read(buffer);
232. }
233. //注，在使用缓冲流写压缩文件时，一个条件完后一定要刷新一把，不
234. //然可能有的内容就会存入到后面条目中去了
235. bo.flush();
236. //文件读完后关闭
237. bi.close();
238. }
239. }
240. }

 

要想把文件加入压缩包，你必须将ZipEntry对象传给 putNextEntry( )。ZipEntry是一个接口很复杂的对象，它能让你设置和读取Zip文件里的某条记录的信息，这些信息包括：文件名，压缩前和压缩后的大小，日 期，CRC校验码，附加字段，注释，压缩方法，是否是目录。虽然标准的Zip格式是支持口令的，但是Java的Zip类库却不支持。而且ZipEntry 却只提供了CRC的接口，而CheckedInputStream和CheckedOutputStream却支持Adler32和CRC32两种校验 码。虽然这是底层的Zip格式的限制，但却妨碍了你使用更快的Adler32了。

要想提取文件，可以用ZipInputStream的getNextEntry( )方法。只要压缩包里还有ZipEntry，它就会把它提取出来。此外还有一个更简洁的办法，你可以用ZipFile对象去读文件。ZipFile有一个 entries()方法，它可以返回ZipEntries的Enumeration。然后通过zipFile. getInputStream(ZipEntry entry)获取压缩流就可以读取相应条目了。

要想读取校验码，必须先获取Checksum对象。我们这里用的是CheckedOutputStream和CheckedInputStream，不过 你也可以使用Checksum。java.util.zip包中比较重要校验算法类是Adler32和CRC32，它们实现了 java.util.zip.Checksum接口，并估算了压缩数据的校验和（checksum）。在运算速度方面，Adler32算法比CRC32算 法要有一定的优势；但在数据可信度方面，CRC32算法则要更胜一筹。GetValue方法可以用来获得当前的checksum值，reset方法能够重 新设置checksum为其缺省的值。

校验和一般用来校验文件和信息是否正确的传送。举个例子，假设你想创建一个ZIP文件，然后将其传送到远程计算机上。当到达远程计算机后，你就可以使用checksum检验在传输过程中文件是否发生错误，有点像下载文件后我们可以使用哈希值来校验文件下载过程是否出错了。

Zip类里还有一个让人莫名其妙的setComment( )方法。如ZipCompress.java所示，写文件的时候，你可以加注释，但是读文件的时候，ZipInputSream却不提供接口。看来它的注释功能完全是针对条目的，是用ZipEntry实现的。

当然，GZIP和Zip不光能用来压缩文件——它还能压缩任何东西，包括要通过网络传输的数据。

(转自:http://jiangzhengjun.iteye.com/blog/517186)