配色: 字号:
使用java基础类实现zip压缩和zip解压工具类分享
2016-10-08 | 阅:  转:  |  分享 
  
使用java基础类实现zip压缩和zip解压工具类分享

使用java基础类写的一个简单的zip压缩解压工具类,实现了指定目录压缩到和该目录同名的zip文件和将zip文件解压到指定的目录的功能

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

复制代码代码如下:

packagesun.net.helper;

importjava.io.;importjava.util.logging.Logger;importjava.util.zip.;publicclassZipUtil{privatefinalstaticLoggerlogger=Logger.getLogger(ZipUtil.class.getName());privatestaticfinalintBUFFER=102410;

/将指定目录压缩到和该目录同名的zip文件,自定义压缩路径@paramsourceFilePath目标文件路径@paramzipFilePath指定zip文件路径@return/publicstaticbooleanzip(StringsourceFilePath,StringzipFilePath){booleanresult=false;Filesource=newFile(sourceFilePath);if(!source.exists()){logger.info(sourceFilePath+"doesn''texist.");returnresult;}if(!source.isDirectory()){logger.info(sourceFilePath+"isnotadirectory.");returnresult;}FilezipFile=newFile(zipFilePath+"/"+source.getName()+".zip");if(zipFile.exists()){logger.info(zipFile.getName()+"isalreadyexist.");returnresult;}else{if(!zipFile.getParentFile().exists()){if(!zipFile.getParentFile().mkdirs()){logger.info("cann''tcreatefile"+zipFile.getName());returnresult;}}}logger.info("creatingzipfile...");FileOutputStreamdest=null;ZipOutputStreamout=null;try{dest=newFileOutputStream(zipFile);CheckedOutputStreamchecksum=newCheckedOutputStream(dest,newAdler32());out=newZipOutputStream(newBufferedOutputStream(checksum));out.setMethod(ZipOutputStream.DEFLATED);compress(source,out,source.getName());result=true;}catch(FileNotFoundExceptione){e.printStackTrace();}finally{if(out!=null){try{out.closeEntry();}catch(IOExceptione){e.printStackTrace();}try{out.close();}catch(IOExceptione){e.printStackTrace();}}}if(result){logger.info("done.");}else{logger.info("fail.");}returnresult;}privatestaticvoidcompress(Filefile,ZipOutputStreamout,StringmainFileName){if(file.isFile()){FileInputStreamfi=null;BufferedInputStreamorigin=null;try{fi=newFileInputStream(file);origin=newBufferedInputStream(fi,BUFFER);intindex=file.getAbsolutePath().indexOf(mainFileName);StringentryName=file.getAbsolutePath().substring(index);System.out.println(entryName);ZipEntryentry=newZipEntry(entryName);out.putNextEntry(entry);byte[]data=newbyte[BUFFER];intcount;while((count=origin.read(data,0,BUFFER))!=-1){out.write(data,0,count);}}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{if(origin!=null){try{origin.close();}catch(IOExceptione){e.printStackTrace();}}}}elseif(file.isDirectory()){File[]fs=file.listFiles();if(fs!=null&&fs.length>0){for(Filef:fs){compress(f,out,mainFileName);}}}}

/将zip文件解压到指定的目录,该zip文件必须是使用该类的zip方法压缩的文件@paramzipFile@paramdestPath@return/publicstaticbooleanunzip(FilezipFile,StringdestPath){booleanresult=false;if(!zipFile.exists()){logger.info(zipFile.getName()+"doesn''texist.");returnresult;}Filetarget=newFile(destPath);if(!target.exists()){if(!target.mkdirs()){logger.info("cann''tcreatefile"+target.getName());returnresult;}}StringmainFileName=zipFile.getName().replace(".zip","");FiletargetFile=newFile(destPath+"/"+mainFileName);if(targetFile.exists()){logger.info(targetFile.getName()+"alreadyexist.");returnresult;}ZipInputStreamzis=null;logger.info("startunzipfile...");try{FileInputStreamfis=newFileInputStream(zipFile);CheckedInputStreamchecksum=newCheckedInputStream(fis,newAdler32(www.sm136.com));zis=newZipInputStream(newBufferedInputStream(checksum));ZipEntryentry;while((entry=zis.getNextEntry())!=null){intcount;bytedata[]=newbyte[BUFFER];StringentryName=entry.getName();intindex=entryName.indexOf(mainFileName);StringnewEntryName=destPath+"/"+entryName.substring(index);System.out.println(newEntryName);Filetemp=newFile(newEntryName).getParentFile();if(!temp.exists()){if(!temp.mkdirs()){thrownewRuntimeException("createfile"+temp.getName()+"fail");}}FileOutputStreamfos=newFileOutputStream(newEntryName);BufferedOutputStreamdest=newBufferedOutputStream(fos,BUFFER);while((count=zis.read(data,0,BUFFER))!=-1){dest.write(data,0,count);}dest.flush();dest.close();}result=true;}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{if(zis!=null){try{zis.close();}catch(IOExceptione){e.printStackTrace();}}}if(result){logger.info("done.");}else{logger.info("fail.");}returnresult;}publicstaticvoidmain(String[]args)throwsIOException{//ZipUtil.zip("D:/apache-tomcat-7.0.30","d:/temp");FilezipFile=newFile("D:/temp/apache-tomcat-7.0.30.zip");ZipUtil.unzip(zipFile,"d:/temp");}}



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

复制代码代码如下:

packagecom.lanp;

importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.zip.ZipEntry;importjava.util.zip.ZipException;importjava.util.zip.ZipFile;importjava.util.zip.ZipInputStream;

/解压ZIP压缩文件到指定的目录/publicfinalclassZipToFile{/缓存区大小默认20480/privatefinalstaticintFILE_BUFFER_SIZE=20480;privateZipToFile(){}/将指定目录的ZIP压缩文件解压到指定的目录@paramzipFilePathZIP压缩文件的路径@paramzipFileNameZIP压缩文件名字@paramtargetFileDirZIP压缩文件要解压到的目录@returnflag布尔返回值/publicstaticbooleanunzip(StringzipFilePath,StringzipFileName,StringtargetFileDir){booleanflag=false;//1.判断压缩文件是否存在,以及里面的内容是否为空Filefile=null;//压缩文件(带路径)ZipFilezipFile=null;file=newFile(zipFilePath+"/"+zipFileName);System.out.println(">>>>>>解压文件【"+zipFilePath+"/"+zipFileName+"】到【"+targetFileDir+"】目录下<<<<<<");if(false==file.exists(www.visa158.com)){System.out.println(">>>>>>压缩文件【"+zipFilePath+"/"+zipFileName+"】不存在<<<<<<");returnfalse;}elseif(0==file.length()){System.out.println(">>>>>>压缩文件【"+zipFilePath+"/"+zipFileName+"】大小为0不需要解压<<<<<<");returnfalse;}else{//2.开始解压ZIP压缩文件的处理byte[]buf=newbyte[FILE_BUFFER_SIZE];intreadSize=-1;ZipInputStreamzis=null;FileOutputStreamfos=null;try{//检查是否是zip文件zipFile=newZipFile(file);zipFile.close();//判断目标目录是否存在,不存在则创建Filenewdir=newFile(targetFileDir);if(false==newdir.exists()){newdir.mkdirs();newdir=null;}zis=newZipInputStream(newFileInputStream(file));ZipEntryzipEntry=zis.getNextEntry();//开始对压缩包内文件进行处理while(null!=zipEntry){StringzipEntryName=zipEntry.getName(www.hunanwang.net).replace(''\\'',''/'');//判断zipEntry是否为目录,如果是,则创建if(zipEntry.isDirectory()){intindexNumber=zipEntryName.lastIndexOf(''/'');FileentryDirs=newFile(targetFileDir+"/"+zipEntryName.substring(0,indexNumber));entryDirs.mkdirs();entryDirs=null;}else{try{fos=newFileOutputStream(targetFileDir+"/"+zipEntryName);while((readSize=zis.read(buf,0,FILE_BUFFER_SIZE))!=-1){fos.write(buf,0,readSize);}}catch(Exceptione){e.printStackTrace();thrownewRuntimeException(e.getCause());}finally{try{if(null!=fos){fos.close();}}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e.getCause());}}}zipEntry=zis.getNextEntry();}flag=true;}catch(ZipExceptione){e.printStackTrace();thrownewRuntimeException(e.getCause());}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e.getCause());}finally{try{if(null!=zis){zis.close();}if(null!=fos){fos.close();}}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e.getCause());}}}returnflag;}

/测试用的Main方法/publicstaticvoidmain(String[]args){StringzipFilePath="C:\\home";StringzipFileName="lp20120301.zip";StringtargetFileDir="C:\\home\\lp20120301";booleanflag=ZipToFile.unzip(zipFilePath,zipFileName,targetFileDir);if(flag){System.out.println(">>>>>>解压成功<<<<<<");}else{System.out.println(">>>>>>解压失败<<<<<<");}}

}























献花(0)
+1
(本文系白狐一梦首藏)