Java实现的zip压缩及解压缩工具类示例
本文实例讲述了Java实现的zip压缩及解压缩工具类。分享给大家供大家参考,具体如下:
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Enumeration;
importorg.apache.tools.zip.ZipEntry;
importorg.apache.tools.zip.ZipFile;
importorg.apache.tools.zip.ZipOutputStream;
publicclassZipUtil{
privatestaticfinalintBUFFEREDSIZE=1024;
/**
*压缩文件
*
*@paramzipFileName
*保存的压缩包文件路径
*@paramfilePath
*需要压缩的文件夹或者文件路径
*@paramisDelete
*是否删除源文件
*@throwsException
*/
publicvoidzip(StringzipFileName,StringfilePath,booleanisDelete)throwsException{
zip(zipFileName,newFile(filePath),isDelete);
}
/**
*压缩文件
*
*@paramzipFileName
*保存的压缩包文件路径
*@paraminputFile
*需要压缩的文件夹或者文件
*@paramisDelete
*是否删除源文件
*@throwsException
*/
publicvoidzip(StringzipFileName,FileinputFile,booleanisDelete)throwsException{
ZipOutputStreamout=newZipOutputStream(newFileOutputStream(zipFileName));
if(!inputFile.exists()){
thrownewFileNotFoundException("在指定路径未找到需要压缩的文件!");
}
zip(out,inputFile,"",isDelete);
out.close();
}
/**
*递归压缩方法
*
*@paramout
*压缩包输出流
*@paramf
*需要压缩的文件
*@parambase
*压缩的路径
*@paramisDelete
*是否删除源文件
*@throwsException
*/
privatevoidzip(ZipOutputStreamout,FileinputFile,Stringbase,booleanisDelete)throwsException{
if(inputFile.isDirectory()){//如果是目录
File[]inputFiles=inputFile.listFiles();
out.putNextEntry(newZipEntry(base+"/"));
base=base.length()==0?"":base+"/";
for(inti=0;i0){
out.putNextEntry(newZipEntry(base));
}else{
out.putNextEntry(newZipEntry(inputFile.getName()));
}
FileInputStreamin=newFileInputStream(inputFile);
try{
intlen;
byte[]buff=newbyte[BUFFEREDSIZE];
while((len=in.read(buff))!=-1){
out.write(buff,0,len);
}
}catch(IOExceptione){
throwe;
}finally{
in.close();
}
}
if(isDelete){
inputFile.delete();
}
}
/**
*解压缩
*
*@paramzipFilePath
*压缩包路径
*@paramfileSavePath
*解压路径
*@paramisDelete
*是否删除源文件
*@throwsException
*/
publicvoidunZip(StringzipFilePath,StringfileSavePath,booleanisDelete)throwsException{
try{
(newFile(fileSavePath)).mkdirs();
Filef=newFile(zipFilePath);
if((!f.exists())&&(f.length()<=0)){
thrownewException("要解压的文件不存在!");
}
ZipFilezipFile=newZipFile(f);
StringstrPath,gbkPath,strtemp;
FiletempFile=newFile(fileSavePath);//从当前目录开始
strPath=tempFile.getAbsolutePath();//输出的绝对位置
Enumeratione=zipFile.getEntries();
while(e.hasMoreElements()){
org.apache.tools.zip.ZipEntryzipEnt=e.nextElement();
gbkPath=zipEnt.getName();
if(zipEnt.isDirectory()){
strtemp=strPath+File.separator+gbkPath;
Filedir=newFile(strtemp);
dir.mkdirs();
continue;
}else{
//读写文件
InputStreamis=zipFile.getInputStream(zipEnt);
BufferedInputStreambis=newBufferedInputStream(is);
gbkPath=zipEnt.getName();
strtemp=strPath+File.separator+gbkPath;
//建目录
Stringstrsubdir=gbkPath;
for(inti=0;i
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。