使用ant解压缩包、打压缩包

需要用到的jar包:

 ant.jar

1、解压缩包:

/**
 * 解压指定zip文件 
 * @param unZipfile:需要解压缩的压缩包路径(路径+名称+.+后缀名)
 * @param destFile:解压到的目录
 * */
public void UNCompress(File unZipfile, File destFile) {
	FileOutputStream fileOut;
    File file;
    InputStream inputStream;
    ZipFile zipFile=null;
    ZipOutputStream zipOut=null;     //压缩Zip
    try {
        //生成一个zip的文件
        zipFile = new ZipFile(unZipfile,"GBK");//设置编码,避免出现中文的情况(不管是压缩文件为中文,还是压缩包中的文件为中文)
        //遍历zipFile中所有的实体,并把他们解压出来
        for (@SuppressWarnings("unchecked")
        Enumeration<ZipEntry> entries = zipFile.getEntries(); entries.hasMoreElements();) {
            ZipEntry entry =  entries.nextElement();
            //生成他们解压后的一个文件  
            file = new File(destFile+File.separator+entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                File parent = file.getParentFile();// 如果指定文件的目录不存在,就创建.
                if (!parent.exists()) {
                    parent.mkdirs();
                }  
                //获取出该压缩实体的输入流 
                    inputStream = zipFile.getInputStream(entry);
  
                    fileOut = new FileOutputStream(file);
                    int length = 0;
                    //将实体写到本地文件中去
                while ((length = inputStream.read(buf)) > 0) {
                    fileOut.write(buf, 0, length);
                }
                fileOut.close();
                inputStream.close();
            }
        }
        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

2、打压缩包:

/**
 * 打压缩包
 * @param classFileList:需要打成压缩包的文件夹路径
 * */
public void compress(List<File> classFileList) {  
	String srcPathName=null;//需要打成压缩包的文件夹路径
	File zipFile=null;//压缩包名称(路径+名称+.+后缀名)
	File srcdir=null;
	Project prj=null;
	Zip zip = null;
	if(classFileList!=null && classFileList.size()>0){
		for(File f:classFileList){
			//System.out.println(f.getAbsolutePath()+"\n"+f.getName());
			srcPathName = f.getAbsolutePath();
			//System.out.println(f.getAbsolutePath()+File.separator+f.getName()+".zip");
			zipFile = new File(f.getAbsolutePath()+".zip") ;
			
			srcdir= new File(srcPathName);  
	        if (!srcdir.exists()){  
	            throw new RuntimeException(srcPathName + "不存在!");  
	        }
	        if(zipFile.exists()){//说明当前目录下存在同名压缩文件
	        	zipFile.delete();
	        }
	        prj = new Project();  
	        zip = new Zip();  
	        zip.setEncoding("GBK");//设置编码,防止压缩文件名字乱码,还有被压缩文件的乱码
	        zip.setProject(prj);  
	        zip.setDestFile(zipFile);  
	        FileSet fileSet = new FileSet();  
	        fileSet.setProject(prj);  
	        fileSet.setDir(srcdir);  
	        zip.addFileset(fileSet);  
	        zip.execute();  //执行生成
		}
	}
}

猜你喜欢

转载自1017401036.iteye.com/blog/2258628