---
title: "java压缩文件夹下的所有文件和选定文件"
author: "linsl"
date: "2010-12-08T12:02:52Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-12-08T12:02:52Z"
id: 836526
url: "https://linsl.iteye.com/blog/836526"
---

01. package zip;
02. import java.io.File;
03. import java.io.FileInputStream;
04. import java.io.FileOutputStream;
05. import org.apache.tools.zip.ZipEntry;
06. import org.apache.tools.zip.ZipOutputStream;
07. public class test {
08. /\**
09. \*
10. * @param inputFileName 输入一个文件夹
11. * @param zipFileName   输出一个压缩文件夹，打包后文件名字
12. * @throws Exception
13. \*/
14. public void zip(String inputFileName, String zipFileName) throws Exception {
15. System.out.println(zipFileName);
16. zip(zipFileName, new File(inputFileName));
17. }
18. private void zip(String zipFileName, File inputFile) throws Exception {
19. ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
20. zipFileName));
21. zip(out, inputFile, "");
22. System.out.println("zip done");
23. out.close();
24. }
25. private void zip(ZipOutputStream out, File f, String base) throws Exception {
26. if (f.isDirectory()) {  //判断是否为目录
27. File\[] fl = f.listFiles();
28. //            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
29. out.putNextEntry(new ZipEntry(base + "/"));
30. base = base.length() == 0 ? "" : base + "/";
31. for (int i = 0; i &lt; fl.length; i++) {
32. zip(out, fl\[i], base + fl\[i].getName());
33. }
34. } else {                //压缩目录中的所有文件
35. //            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
36. out.putNextEntry(new ZipEntry(base));
37. FileInputStream in = new FileInputStream(f);
38. int b;
39. System.out.println(base);
40. while ((b = in.read()) != -1) {
41. out.write(b);
42. }
43. in.close();
44. }
45. }
46. public static void main(String\[] temp) {
47. String inputFileName = "F:\\\\xxx\\\\excel\\\\多文件合并测试";    //你要压缩的文件夹
48. String zipFileName = "D:\\\\test.zip";  //压缩后的zip文件
49. test book = new test();
50. try {
51. book.zip(inputFileName, zipFileName);
52. } catch (Exception ex) {
53. ex.printStackTrace();
54. }
55. }
56. }