欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用java基础类实现zip压缩和zip解压工具类分享

程序员文章站 2024-02-23 22:26:28
使用java基础类写的一个简单的zip压缩解压工具类复制代码 代码如下:package sun.net.helper; import java.io.*;import j...

使用java基础类写的一个简单的zip压缩解压工具类

复制代码 代码如下:

package sun.net.helper;

import java.io.*;
import java.util.logging.logger;
import java.util.zip.*;

public class ziputil {
    private final static logger logger = logger.getlogger(ziputil.class.getname());
    private static final int buffer = 1024*10;

    /**
     * 将指定目录压缩到和该目录同名的zip文件,自定义压缩路径
     * @param sourcefilepath  目标文件路径
     * @param zipfilepath     指定zip文件路径
     * @return
     */
    public static boolean zip(string sourcefilepath,string zipfilepath){
        boolean result=false;
        file source=new file(sourcefilepath);
        if(!source.exists()){
            logger.info(sourcefilepath+" doesn't exist.");
            return result;
        }
        if(!source.isdirectory()){
            logger.info(sourcefilepath+" is not a directory.");
            return result;
        }
        file zipfile=new file(zipfilepath+"/"+source.getname()+".zip");
        if(zipfile.exists()){
            logger.info(zipfile.getname()+" is already exist.");
            return result;
        }else{
            if(!zipfile.getparentfile().exists()){
                if(!zipfile.getparentfile().mkdirs()){
                    logger.info("cann't create file "+zipfile.getname());
                    return result;
                }
            }
        }
        logger.info("creating zip file...");
        fileoutputstream dest=null;
        zipoutputstream out =null;
        try {
            dest = new fileoutputstream(zipfile);
            checkedoutputstream checksum = new checkedoutputstream(dest, new adler32());
            out=new zipoutputstream(new bufferedoutputstream(checksum));
            out.setmethod(zipoutputstream.deflated);
            compress(source,out,source.getname());
            result=true;
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        }finally {
            if (out != null) {
                try {
                    out.closeentry();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
                try {
                    out.close();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    private static void compress(file file,zipoutputstream out,string mainfilename) {
        if(file.isfile()){
            fileinputstream fi= null;
            bufferedinputstream origin=null;
            try {
                fi = new fileinputstream(file);
                origin=new bufferedinputstream(fi, buffer);
                int index=file.getabsolutepath().indexof(mainfilename);
                string entryname=file.getabsolutepath().substring(index);
                system.out.println(entryname);
                zipentry entry = new zipentry(entryname);
                out.putnextentry(entry);
                byte[] data = new byte[buffer];
                int count;
                while((count = origin.read(data, 0, buffer)) != -1) {
                    out.write(data, 0, count);
                }
            } catch (filenotfoundexception e) {
                e.printstacktrace();
            } catch (ioexception e) {
                e.printstacktrace();
            }finally {
                if (origin != null) {
                    try {
                        origin.close();
                    } catch (ioexception e) {
                        e.printstacktrace();
                    }
                }
            }
        }else if (file.isdirectory()){
            file[] fs=file.listfiles();
            if(fs!=null&&fs.length>0){
                for(file f:fs){
                    compress(f,out,mainfilename);
                }
            }
        }
    }

    /**
     * 将zip文件解压到指定的目录,该zip文件必须是使用该类的zip方法压缩的文件
     * @param zipfile
     * @param destpath
     * @return
     */
    public static boolean unzip(file zipfile,string destpath){
        boolean result=false;
        if(!zipfile.exists()){
            logger.info(zipfile.getname()+" doesn't exist.");
            return result;
        }
        file target=new file(destpath);
        if(!target.exists()){
            if(!target.mkdirs()){
                logger.info("cann't create file "+target.getname());
                return result;
            }
        }
        string mainfilename=zipfile.getname().replace(".zip","");
        file targetfile=new file(destpath+"/"+mainfilename);
        if(targetfile.exists()){
            logger.info(targetfile.getname()+" already exist.");
            return result;
        }
        zipinputstream zis =null;
        logger.info("start unzip file ...");
        try {
            fileinputstream fis= new fileinputstream(zipfile);
            checkedinputstream checksum = new checkedinputstream(fis, new adler32());
            zis = new zipinputstream(new bufferedinputstream(checksum));
            zipentry entry;
            while((entry = zis.getnextentry()) != null) {
                int count;
                byte data[] = new byte[buffer];
                string entryname=entry.getname();
                int index=entryname.indexof(mainfilename);
                string newentryname=destpath+"/"+entryname.substring(index);
                system.out.println(newentryname);
                file temp=new file(newentryname).getparentfile();
                if(!temp.exists()){
                    if(!temp.mkdirs()){
                        throw new runtimeexception("create file "+temp.getname() +" fail");
                    }
                }
                fileoutputstream fos = new fileoutputstream(newentryname);
                bufferedoutputstream dest = new bufferedoutputstream(fos,buffer);
                while ((count = zis.read(data, 0, buffer)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
            result=true;
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    public static void main(string[] args) throws ioexception {
        //ziputil.zip("d:/apache-tomcat-7.0.30", "d:/temp");
        file zipfile=new file("d:/temp/apache-tomcat-7.0.30.zip");
        ziputil.unzip(zipfile,"d:/temp") ;
    }
}



另一个压缩解压示例,二个工具大家参考使用吧

复制代码 代码如下:

package com.lanp;

import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.zip.zipentry;
import java.util.zip.zipexception;
import java.util.zip.zipfile;
import java.util.zip.zipinputstream;

/**
 * 解压zip压缩文件到指定的目录
 */
public final class ziptofile {
 /**
  * 缓存区大小默认20480
  */
 private final static int file_buffer_size = 20480;

 private ziptofile() {

 }

 /**
  * 将指定目录的zip压缩文件解压到指定的目录
  * @param zipfilepath  zip压缩文件的路径
  * @param zipfilename  zip压缩文件名字
  * @param targetfiledir  zip压缩文件要解压到的目录
  * @return flag    布尔返回值
  */
 public static boolean unzip(string zipfilepath, string zipfilename, string targetfiledir){
  boolean flag = false;
  //1.判断压缩文件是否存在,以及里面的内容是否为空
  file file = null;   //压缩文件(带路径)
  zipfile zipfile = null;
  file = new file(zipfilepath + "/" + zipfilename);
  system.out.println(">>>>>>解压文件【" + zipfilepath + "/" + zipfilename + "】到【" + targetfiledir + "】目录下<<<<<<");
  if(false == file.exists()) {
   system.out.println(">>>>>>压缩文件【" + zipfilepath + "/" + zipfilename + "】不存在<<<<<<");
   return false;
  } else if(0 == file.length()) {
   system.out.println(">>>>>>压缩文件【" + zipfilepath + "/" + zipfilename + "】大小为0不需要解压<<<<<<");
   return false;
  } else {
   //2.开始解压zip压缩文件的处理
   byte[] buf = new byte[file_buffer_size];
   int readsize = -1;
   zipinputstream zis = null;
   fileoutputstream fos = null;
   try {
    // 检查是否是zip文件
    zipfile = new zipfile(file);
    zipfile.close();
    // 判断目标目录是否存在,不存在则创建
    file newdir = new file(targetfiledir);
    if (false == newdir.exists()) {
     newdir.mkdirs();
     newdir = null;
    }
    zis = new zipinputstream(new fileinputstream(file));
    zipentry zipentry = zis.getnextentry();
    // 开始对压缩包内文件进行处理
    while (null != zipentry) {
     string zipentryname = zipentry.getname().replace('\\', '/');
     //判断zipentry是否为目录,如果是,则创建
     if(zipentry.isdirectory()) {
      int indexnumber = zipentryname.lastindexof('/');
      file entrydirs = new file(targetfiledir + "/" + zipentryname.substring(0, indexnumber));
      entrydirs.mkdirs();
      entrydirs = null;
     } else {
      try {
       fos = new fileoutputstream(targetfiledir + "/" + zipentryname);
       while ((readsize = zis.read(buf, 0, file_buffer_size)) != -1) {
        fos.write(buf, 0, readsize);
       }
      } catch (exception e) {
       e.printstacktrace();
       throw new runtimeexception(e.getcause());
      } finally {
       try {
        if (null != fos) {
         fos.close();
        }
       } catch (ioexception e) {
        e.printstacktrace();
        throw new runtimeexception(e.getcause());
       }
      }
     }
     zipentry = zis.getnextentry();
    }
    flag = true;
   } catch (zipexception e) {
    e.printstacktrace();
    throw new runtimeexception(e.getcause());
   } catch (ioexception e) {
    e.printstacktrace();
    throw new runtimeexception(e.getcause());
   } finally {
    try {
     if (null != zis) {
      zis.close();
     }
     if (null != fos) {
      fos.close();
     }
    } catch (ioexception e) {
     e.printstacktrace();
     throw new runtimeexception(e.getcause());
    }
   }
  }
  return flag;
 }

 /**
  * 测试用的main方法
  */
 public static void main(string[] args) {
  string zipfilepath = "c:\\home";
  string zipfilename = "lp20120301.zip";
  string targetfiledir = "c:\\home\\lp20120301";
  boolean flag = ziptofile.unzip(zipfilepath, zipfilename, targetfiledir);
  if(flag) {
   system.out.println(">>>>>>解压成功<<<<<<");
  } else {
   system.out.println(">>>>>>解压失败<<<<<<");
  }
 }

}