Java對zip,rar,7z文件帶密碼解壓實例詳解_第1頁
Java對zip,rar,7z文件帶密碼解壓實例詳解_第2頁
Java對zip,rar,7z文件帶密碼解壓實例詳解_第3頁
Java對zip,rar,7z文件帶密碼解壓實例詳解_第4頁
Java對zip,rar,7z文件帶密碼解壓實例詳解_第5頁
已閱讀5頁,還剩8頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

第Java對zip,rar,7z文件帶密碼解壓實例詳解目錄前言實現(xiàn)代碼1、pom.xml2、zip解壓3、rar解壓4、7z解壓5、解壓統(tǒng)一入口封裝6、測試代碼補充

前言

在一些日常業(yè)務(wù)中,會遇到一些瑣碎文件需要統(tǒng)一打包到一個壓縮包中上傳,業(yè)務(wù)方在后臺接收到壓縮包后自行解壓,然后解析相應文件。而且可能涉及安全保密,因此會在壓縮時帶上密碼,要求后臺業(yè)務(wù)可以指定密碼進行解壓。

應用環(huán)境說明:jdk1.8,maven3.x,需要基于java語言實現(xiàn)對zip、rar、7z等常見壓縮包的解壓工作。

首先關(guān)于zip和rar、7z等壓縮工具和壓縮算法就不在此贅述,下面通過一個數(shù)據(jù)對比,使用上述三種不同的壓縮算法,采用默認的壓縮方式,看到壓縮的文件大小如下:

轉(zhuǎn)換成圖表看得更直觀,如下圖:

從以上圖表可以看到,7z的壓縮率是最高,而zip壓縮率比較低,rar比zip稍微好點。單純從壓縮率看,7zrar4rar5zip。

實現(xiàn)代碼

下面具體說明在java中如何進行相應解壓:

1、pom.xml

projectxmlns="/POM/4.0.0"

xmlns:xsi="/2001/XMLSchema-instance"

xsi:schemaLocation="/POM/4.0.0/xsd/maven-4.0.0.xsd"

modelVersion4.0.0/modelVersion

groupIdcom.yelang/groupId

artifactId7zdemo/artifactId

version0.0.1-SNAPSHOT/version

dependencies

dependency

groupIdnet.lingala.zip4j/groupId

artifactIdzip4j/artifactId

version2.9.0/version

/dependency

dependency

groupIdnet.sf.sevenzipjbinding/groupId

artifactIdsevenzipjbinding/artifactId

version16.02-2.01/version

/dependency

dependency

groupIdnet.sf.sevenzipjbinding/groupId

artifactIdsevenzipjbinding-all-platforms/artifactId

version16.02-2.01/version

/dependency

dependency

groupIdorg.tukaani/groupId

artifactIdxz/artifactId

version1.9/version

/dependency

dependency

groupIdmons/groupId

artifactIdcommons-compress/artifactId

version1.21/version

/dependency

!--/artifact/org.slf4j/slf4j-api--

dependency

groupIdorg.slf4j/groupId

artifactIdslf4j-api/artifactId

version1.7.30/version

/dependency

!--/artifact/mons/commons-lang3--

dependency

groupIdmons/groupId

artifactIdcommons-lang3/artifactId

version3.12.0/version

/dependency

!--/artifact/fr.opensagres.xdocreport/xdocreport--

dependency

groupIdfr.opensagres.xdocreport/groupId

artifactIdxdocreport/artifactId

version1.0.6/version

/dependency

/dependencies

/project

主要依賴的jar包有:zip4j、sevenzipjbinding等。

2、zip解壓

@SuppressWarnings("resource")

privatestaticStringunZip(StringrootPath,StringsourceRarPath,StringdestDirPath,StringpassWord){

ZipFilezipFile=null;

Stringresult="";

try{

//StringfilePath=sourceRarPath;

StringfilePath=rootPath+sourceRarPath;

if(StringUtils.isNotBlank(passWord)){

zipFile=newZipFile(filePath,passWord.toCharArray());

}else{

zipFile=newZipFile(filePath);

zipFile.setCharset(Charset.forName("GBK"));

zipFile.extractAll(rootPath+destDirPath);

}catch(Exceptione){

log.error("unZiperror",e);

returne.getMessage();

returnresult;

3、rar解壓

privatestaticStringunRar(StringrootPath,StringsourceRarPath,StringdestDirPath,StringpassWord){

StringrarDir=rootPath+sourceRarPath;

StringoutDir=rootPath+destDirPath+File.separator;

RandomAccessFilerandomAccessFile=null;

IInArchiveinArchive=null;

try{

//第一個參數(shù)是需要解壓的壓縮包路徑,第二個參數(shù)參考JdkAPI文檔的RandomAccessFile

randomAccessFile=newRandomAccessFile(rarDir,"r");

if(StringUtils.isNotBlank(passWord))

inArchive=SevenZip.openInArchive(null,newRandomAccessFileInStream(randomAccessFile),passWord);

else

inArchive=SevenZip.openInArchive(null,newRandomAccessFileInStream(randomAccessFile));

ISimpleInArchivesimpleInArchive=inArchive.getSimpleInterface();

for(finalISimpleInArchiveItemitem:simpleInArchive.getArchiveItems()){

finalint[]hash=newint[]{0};

if(!item.isFolder()){

ExtractOperationResultresult;

finallong[]sizeArray=newlong[1];

FileoutFile=newFile(outDir+item.getPath());

Fileparent=outFile.getParentFile();

if((!parent.exists())(!parent.mkdirs())){

continue;

if(StringUtils.isNotBlank(passWord)){

result=item.extractSlow(data-{

try{

IOUtils.write(data,newFileOutputStream(outFile,true));

}catch(Exceptione){

e.printStackTrace();

hash[0]^=Arrays.hashCode(data);//Consumedata

sizeArray[0]+=data.length;

returndata.length;//Returnamountofconsumed

},passWord);

}else{

result=item.extractSlow(data-{

try{

IOUtils.write(data,newFileOutputStream(outFile,true));

}catch(Exceptione){

e.printStackTrace();

hash[0]^=Arrays.hashCode(data);//Consumedata

sizeArray[0]+=data.length;

returndata.length;//Returnamountofconsumed

if(result==ExtractOperationResult.OK){

log.error("解壓rar成功...."+String.format("%9X|%10s|%s",hash[0],sizeArray[0],item.getPath()));

}elseif(StringUtils.isNotBlank(passWord)){

log.error("解壓rar成功:密碼錯誤或者其他錯誤...."+result);

return"password";

}else{

return"rarerror";

}catch(Exceptione){

log.error("unRarerror",e);

returne.getMessage();

}finally{

try{

inArchive.close();

randomAccessFile.close();

}catch(Exceptione){

e.printStackTrace();

return"";

4、7z解壓

privatestaticStringun7z(StringrootPath,StringsourceRarPath,StringdestDirPath,StringpassWord){

try{

FilesrcFile=newFile(rootPath+sourceRarPath);//獲取當前壓縮文件

//判斷源文件是否存在

if(!srcFile.exists()){

thrownewException(srcFile.getPath()+"所指文件不存在");

//開始解壓

SevenZFilezIn=null;

if(StringUtils.isNotBlank(passWord)){

zIn=newSevenZFile(srcFile,passWord.toCharArray());

}else{

zIn=newSevenZFile(srcFile);

SevenZArchiveEntryentry=null;

Filefile=null;

while((entry=zIn.getNextEntry())!=null){

if(!entry.isDirectory()){

file=newFile(rootPath+destDirPath,entry.getName());

if(!file.exists()){

newFile(file.getParent()).mkdirs();//創(chuàng)建此文件的上級目錄

OutputStreamout=newFileOutputStream(file);

BufferedOutputStreambos=newBufferedOutputStream(out);

intlen=-1;

byte[]buf=newbyte[1024];

while((len=zIn.read(buf))!=-1){

bos.write(buf,0,len);

//關(guān)流順序,先打開的后關(guān)閉

bos.close();

out.close();

}catch(Exceptione){

log.error("un7ziserror",e);

returne.getMessage();

return"";

5、解壓統(tǒng)一入口封裝

publicstaticMapString,ObjectunFile(StringrootPath,StringsourcePath,StringdestDirPath,StringpassWord){

MapString,ObjectresultMap=newHashMapString,Object

Stringresult="";

if(sourcePath.toLowerCase().endsWith(".zip")){

//Wrongpassword!

result=unZip(rootPath,sourcePath,destDirPath,passWord);

}elseif(sourcePath.toLowerCase().endsWith(".rar")){

//java.security.InvalidAlgorithmParameterException:passwordshouldbespecified

result=unRar(rootPath,sourcePath,destDirPath,passWord);

System.out.println(result);

}elseif(sourcePath.toLowerCase().endsWith(".7z")){

//PasswordRequiredException:CannotreadencryptedcontentfromG:\ziptest\11111111.7zwithoutapassword

result=un7z(rootPath,sourcePath,destDirPath,passWord);

resultMap.put("resultMsg",1);

if(StringUtils.isNotBlank(result)){

if(result.contains("password"))resultMap.put("resultMsg",2);

if(!result.contains("password"))resultMap.put("resultMsg",3);

resultMap.put("files",null);

//System.out.println(result+"==============");

returnresultMap;

6、測試代碼

Longstart=System.currentTimeMillis();

unFile("D:/rarfetch0628/","apache-tomcat-8.5.69.zip","apache-tomcat-zip","222");

longend=System.currentTimeMillis();

System.out.println("zip解壓耗時=="+(end-start)+"毫秒");

System.out.println("============================================================");

Longrar4start=System.currentTimeMillis();

unFile("D:/rarfetch0628/","apache-tomcat-8.5.69-4.rar","apache-tomcat-rar4","222");

longrar4end=System.currentTimeMillis();

System.out.println("rar4解壓耗時=="+(rar4end-rar4start)+"毫秒");

System.out.println("============================================================");

Longrar5start=System.currentTimeMillis();

unFile("D:/rarfetch0628/","apache-tomcat-8.5.69-5.rar","apache-tomcat-rar5","222");

longrar5end=System.currentTimeMillis();

System.out.println("rar5解壓耗時=="+(rar5end-rar5start)+"毫秒");

System.out.println("============================================================");

Longzstart=System.currentTimeMillis();

unFile("D:/rarfetch0628/","apache-tomcat-z","apache-tomcat-7z","222");

longzend=System.currentTimeMillis();

System.out.println("7z解壓耗時=="+(zend-zstart)+"毫秒");

System.out.println("============================================================");

在控制臺中可以看到以下結(jié)果:

總結(jié):本文采用java語言實現(xiàn)了對zip和rar、7z文件的解壓統(tǒng)一算法。并對比了相應的解壓速度,支持傳入密碼進行在線解壓。

本文參考代碼在補充內(nèi)容里,不過代碼直接運行有問題,這里進行了調(diào)整,主要優(yōu)化的點如下:

1、pom.xml遺漏了slf4j、commons-lang3、xdocreport等依賴

2、zip路徑優(yōu)化

3、去掉一些無用信息

4、優(yōu)化異常信息

補充

1.maven引用

dependency

groupIdnet.lingala.zip4j/groupId

artifactIdzip4j/artifactId

version2.9.0/version

/dependency

dependency

groupIdnet.sf.sevenzipjbinding/groupId

artifactIdsevenzipjbinding

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論