版權(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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 天津市紅橋區(qū)2025-2026學年高三上學期期末語文試卷(含答案)
- 化工企業(yè)維修工培訓課件
- 化工企業(yè)不安全行為培訓課件
- 化工儀表工培訓課件
- 鋼結(jié)構(gòu)焊后熱處理技術(shù)要點
- 2026年菏澤單縣事業(yè)單位公開招聘初級綜合類崗位人員(26人)備考考試試題及答案解析
- 2026湖南株洲市國資委選聘市屬監(jiān)管企業(yè)專職外部董事考試參考題庫及答案解析
- 2026年度煙臺市福山區(qū)事業(yè)單位公開招聘工作人員(68人)考試備考試題及答案解析
- 2026北京航空航天大學計算機學院聘用編高級研發(fā)工程師F崗招聘1人備考考試題庫及答案解析
- 養(yǎng)生有關(guān)活動策劃方案(3篇)
- Q-SY 05673-2020 油氣管道滑坡災害監(jiān)測規(guī)范
- 國有企業(yè)落實擴大內(nèi)需戰(zhàn)略的路徑研究
- 技術(shù)規(guī)范評審匯報
- GB/T 462-2023紙、紙板和紙漿分析試樣水分的測定
- 不組織不參與非法集資承諾書
- 2023春國開農(nóng)業(yè)經(jīng)濟基礎(chǔ)單元自測1-16試題及答案
- 2023年高鐵信號車間副主任述職報告
- GB/T 879.4-2000彈性圓柱銷卷制標準型
- GB/T 1957-2006光滑極限量規(guī)技術(shù)條件
- GB 28480-2012飾品有害元素限量的規(guī)定
- 劉一秒演說智慧經(jīng)典(內(nèi)部筆記)
評論
0/150
提交評論