---
title: "带中文的目录压缩成一个zip文件"
author: "逆风的香1314"
date: "2008-12-12T11:23:00Z"
tags: [".net", "Ant", "Apache", "F#", "JDK"]
slug: "zip"
draft: false
lastmod: "2008-12-12T11:23:00Z"
id: 292109
url: "https://wangxiaojs.iteye.com/blog/292109"
---

由于jdk自带的zip类对中文文件名的支持不好，所以使用了ant的工具类。  
网上的大部分都是这样做的，不过不知道为什么，也许是ant版本问题，我用他们的代码依然是中文文件名乱码，经检查发现，需要指定一些输出流的编码方式就可以了。

out.setEncoding("GBK"); // ###### 这句话是关键，指定输出的编码方式

完整的源代码如下

01. import java.io.File;
02. import java.io.FileInputStream;
03. import java.io.FileOutputStream;
04. import org.apache.tools.zip.ZipEntry;
05. import org.apache.tools.zip.ZipOutputStream;
06. /\**
07. * 整个目录的压缩成一个zip文件.&lt;br&gt;
08. * apache-ant-1.7.1
09. \*
10. * @author 老紫竹(JAVA世纪网 java2000.net)
11. \*/
12. public class DirectoryZip {
13. public static void jar(String inputFileName, String outputFileName) throws Exception {
14. ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
15. out.setEncoding("GBK"); // ###### 这句话是关键，指定输出的编码方式
16. File f = new File(inputFileName);
17. jar(out, f, "");
18. out.close();
19. }
20. private static void jar(ZipOutputStream out, File f, String base) throws Exception {
21. if (f.isDirectory()) {
22. File\[] fl = f.listFiles();
23. base = base.length() == 0 ? "" : base + "/"; // 注意，这里用左斜杠
24. out.putNextEntry(new ZipEntry(base));
25. for (int i = 0; i &lt; fl.length; i++) {
26. jar(out, fl\[i], base + fl\[i].getName());
27. }
28. } else {
29. out.putNextEntry(new ZipEntry(base));
30. FileInputStream in = new FileInputStream(f);
31. byte\[] buffer = new byte\[1024];
32. int n = in.read(buffer);
33. while (n != -1) {
34. out.write(buffer, 0, n);
35. n = in.read(buffer);
36. }
37. in.close();
38. }
39. }
40. public static void main(String\[] args) {
41. try {
42. jar("D:\\\\temp", "d://test.zip");
43. } catch (Exception e) {
44. // TODO Auto-generated catch block
45. e.printStackTrace();
46. }
47. }
48. }