日期:2014-05-16 浏览次数:21412 次
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; /** * 利用Apache ant.jar中的zip包进行Zip压缩和解压 */ public class XZouZip { /** * 测试压缩 */ public void testZip(){ File srcFile = new File("c:/upload");//要压缩的文件对象 File targetZipFile = new File("c:/upload.zip");//压缩后的文件名 ZipOutputStream out = null; boolean boo = false;//是否压缩成功 try{ CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream( targetZipFile), new CRC32()); out = new ZipOutputStream(cos); //out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:/uploadd.zip"))); zip(srcFile, out, "", true); boo = true; }catch(IOException ex){ throw new RuntimeException(ex); }finally{ try{ if(out!=null) out.close(); }catch(IOException ex){ throw new RuntimeException("关闭Zip输出流出现异常",ex); }finally{ //清理操作 if(!boo && targetZipFile.exists())//压缩不成功, targetZipFile.delete(); } } } /** * 测试解压缩 */ public void testUnZip(){ File srcZipFile = new File("c:/upload.zip");//要解压缩的zip文件对象 String destDir = "c:/a";//将解压文件对象放置a目录中 boolean boo = false;//是否压缩成功 try { unZip(srcZipFile,destDir); boo = true; } catch (IOException e) { throw new RuntimeException(e); }finally{ //清理操作 if(!boo) deleteDirectory(new File(destDir));//目标文件夹 。清理 } } public static void main(String[] args) throws IOException { XZouZip tool = new XZouZip(); tool.testZip(); //tool.testUnZip(); } /** * 压缩zip文件 * @param file 压缩的文件对象 * @param out 输出ZIP流 * @param dir 相对父目录名称 * @param boo 是否把空目录压缩进去 */ public void zip(File file,ZipOutputStream out,String dir,boolean boo) throws IOException{ if(file.isDirectory()){//是目录 File []listFile = file.listFiles();//得出目录下所有的文件对象 if(listFile.length == 0 && boo){//空目录压缩 out.putNextEntry(new ZipEntry(dir + file.getName() + "/"));//将实体放入输出ZIP流中 System.out.println("压缩." + dir + file.getName() + "/"); return; }else{ for(File cfile: listFile){ zip(cfile,out,dir + file.getName() + "/",boo);//递归压缩 } } }else if(file.isFile()){//是文件 System.out.println("压缩." + dir + file.getName() + "/"); byte[] bt = new byte[2048*2]; ZipEntry ze = new ZipEntry(dir+file.getName());//构建压缩实体 //设置压缩前的文件大小 ze.setSize(file.length()); out.putNextEntry(ze);////将实体放入输出ZIP流中 FileInputStream fis = null; try{ fis = new FileInputStream(file); int i=0; while((i = fis.read(bt)) != -1) {//循环读出并写入输出Zip流中 out.write(bt, 0, i); } }catch(IOException ex){ throw new IOException("写入压缩文件出现异常",ex); }finally{ try{ if (fis != null) fis.close();//关闭输入流 }catch(IOException ex){ throw new IOException("关闭输入流出现异常"); } } } } /** * 解压缩zipFile * @param file 要解压的zip文件对象 * @param outputDir 要解压到某个指定的目录下 * @throws IOException */ public void unZip(File file,String outputDir) throws I