Java压缩

Java压缩工具类:

首先要导入ant.jar包

 1 package com.foster.utils;

 2 

 3 import java.io.File;

 4 

 5 import org.apache.tools.ant.Project;

 6 import org.apache.tools.ant.taskdefs.Zip;

 7 import org.apache.tools.ant.types.FileSet;

 8 

 9 public final class ZipCompressor {

10     private File zipFile;

11     

12     //创建压缩包文件

13     public ZipCompressor(String pathName){

14         zipFile=new File(pathName);

15     }

16     

17     //压缩文件夹下的所有文件

18     public void compress(String srcPathName){

19         File srcdir=new File(srcPathName); 

20         if(!srcdir.exists()){

21             throw new RuntimeException(srcPathName+"不存在!");

22         }

23         

24         Project prj=new Project();

25         Zip zip=new Zip();

26         zip.setProject(prj);

27         zip.setDestFile(zipFile);

28         FileSet fileSet=new FileSet();

29         fileSet.setProject(prj);

30         fileSet.setDir(srcdir);

31         zip.addFileset(fileSet);

32         

33         zip.execute();

34     }

35 }

 

测试类:

 1 package com.foster.utils;

 2 

 3 public class Test {

 4 

 5     public static void main(String[] args) {

 6         test2();

 7     }

 8     static void test2(){

 9         ZipCompressor zip=new ZipCompressor("c:\\test.zip");

10         zip.compress("c:\\test\\");

11         System.out.println("zip finished");

12     }

13 

14 }

 

 

你可能感兴趣的:(java压缩)