1 /////////////////////////////////////////////////////////////////////////////////////
2 //
3 // 程序:ZIP.java
4 //
5 // 描述:对文件压缩、解压
6 //
7 // 时间:2006-12-20
8 //
9 // 待修改 :
10 //(1).做成有界面的模式
11 //(2).加入加密功能
12 //(3).异常捕获,增加程序的强壮性。容错能力有待提高
13 //
14 ////////////////////////////////////////////////////////////////////////////////////
15
16 import java.util.*;
17 import java.util.zip.*;
18 import java.io.*;
19 class ZIP
20 {
21 public void zip (String zipFileName,String inputFile)throws Exception
22 {
23 //从String对象, 得到 File对象
24 zip (zipFileName,new File (inputFile));//调用下面的方法
25 }
26 public void zip (String zipFileName,File inputFile)throws Exception
27 {
28 //从String对象得到 FileOutputStream对象
29 //从FileOutputStream对象 再得到ZipOutputStream
30 ZipOutputStream out = new ZipOutputStream (new FileOutputStream (zipFileName));
31 zip (out,inputFile,"");//调用下面的方法
32 System.out.println ("zip done");
33 out.close ();
34 }
35 //最终压缩方法的入口(前面只是起到参数封装)
36 public void zip (ZipOutputStream out,File f,String base)throws Exception
37 {
38 System.out.println ("Zipping "+f.getName ());
39 //如果是目录的情况
40 if (f.isDirectory ())
41 {
42 File[] fl=f.listFiles ();
43 out.putNextEntry (new ZipEntry (base+"/"));
44 base=base.length ()==0?"":base+"/";
45 for (int i=0;i<fl.length ;i++ )
46 {
47 zip (out,fl[i],base+fl[i].getName ());
48 }
49 }
50 //文件的情况
51 else
52 {
53 out.putNextEntry (new ZipEntry (base));
54 FileInputStream in=new FileInputStream (f);
55 int b;
56 while ((b=in.read ()) != -1)
57 out.write (b);
58 in.close ();
59 }
60
61 }
62
63 public void unzip (String zipFileName,String outputDirectory)throws Exception
64 {
65 ZipInputStream in=new ZipInputStream (new FileInputStream (zipFileName));
66 ZipEntry z;
67 while ((z=in.getNextEntry () )!= null)
68 {
69 System.out.println ("unziping "+z.getName ());
70 if (z.isDirectory ())
71 {
72 String name=z.getName ();
73 name=name.substring (0,name.length ()-1);
74 File f=new File (outputDirectory+File.separator+name);
75 f.mkdir ();
76 System.out.println ("mkdir "+outputDirectory+File.separator+name);
77 }
78 else
79 {
80 File f=new File (outputDirectory+File.separator+z.getName ());
81 f.createNewFile ();
82 FileOutputStream out=new FileOutputStream (f);
83 int b;
84 while ((b=in.read ()) != -1)
85 out.write (b);
86 out.close ();
87 }
88 }
89
90 in.close ();
91 }
92
93 public static void main (String[] args)
94 {
95 try
96 {
97 ZIP t=new ZIP ();
98 //通过文件夹选项来获取参数,那样就更好了。
99 t.zip ("c://test2.zip","c://test2");
100 // t.unzip ("c://test1.zip","c://test2");
101 }
102 catch(Exception e)
103 {e.printStackTrace (System.out);}
104 }
105 }
posted on 2007-02-08 14:25
-274°C 阅读(277)
评论(0) 编辑 收藏 所属分类:
JAVA