Java實現(xiàn)解壓zip和rar包的示例代碼
更新時間:2024年01月15日 14:13:29 作者:Peter447
這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)解壓zip和rar包,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
zip的解壓提供了一種方法,
rar的解壓提供了兩種方法,第一種方法是調(diào)用命令調(diào)用主機安裝的解壓縮工具,
第二種方法,需要注意一下,需要導(dǎo)一個包
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>4.0.0</version>
</dependency>
并且第二種方法,截至2023年,只支持rar4以下版本的解壓,rar5的版本不支持,以后會不會有更新,就不知道了。

try{
File file = new File(filePath);
if(file.getName().endsWith(".zip")){
ZipInputStream zis = new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"));
byte[] buffer = new byte[1024];
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
String entryName = ze.getName();
File extractedFile = new File(ceShiFilePath + entryName);
if (ze.isDirectory()) {
extractedFile.mkdirs();
} else{
FileOutputStream fos = new FileOutputStream(extractedFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
fileList.add(extractedFile);
}
}
zis.closeEntry();
}else if(file.getName().endsWith(".rar")){
String cmd = "D:\\tools\\zip\\UnRAR.exe";
//cmd命令
String unrarCmd = cmd + " x -r -p- -o+ " + file.getAbsolutePath() + " "
+ ceShiFilePath;
Runtime rt = Runtime.getRuntime();
//調(diào)用程序UnRAR解壓程序(Windows)
Process pre = rt.exec(unrarCmd);
//防止文件亂碼
InputStreamReader isr = new InputStreamReader(pre.getInputStream(),"GBK");
BufferedReader bf = new BufferedReader(isr);
String line = null;
while ((line = bf.readLine()) != null) {
line = line.trim();
if ("".equals(line)) {
continue;
}
}
bf.close();
pre.destroy();
}else if(file.getName().endsWith(".rar")){
Archive archive = new Archive(new FileInputStream(file));
List<FileHeader> fileHeaders = archive.getFileHeaders();
for (FileHeader fileHeader : fileHeaders) {
if (fileHeader.isDirectory()) {
File dir = new File(ceShiFilePath + fileHeader.getFileNameString());
if (!dir.exists()){
dir.mkdirs();
}
} else {
String fileName= fileHeader.getFileNameW().trim();
File subFile = new File(ceShiFilePath + fileName);
if (!subFile.exists()) {
if (!subFile.getParentFile().exists()) {
subFile.getParentFile().mkdirs();
}
subFile.createNewFile();
}
FileOutputStream os = new FileOutputStream(subFile);
archive.extractFile(fileHeader, os);
os.close();
fileList.add(subFile);
}
}
archive.close();
}
for(File file111 : fileList){
System.out.println(file111.getAbsolutePath());
}
}catch (Exception ex){
ex.printStackTrace();
log.error(ex.getMessage());
}
都是親測可用的。
到此這篇關(guān)于Java實現(xiàn)解壓zip和rar包的示例代碼的文章就介紹到這了,更多相關(guān)Java解壓zip和rar內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot 使用內(nèi)置tomcat禁止不安全HTTP的方法
這篇文章主要介紹了Springboot 使用內(nèi)置tomcat禁止不安全HTTP的方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java中輕量級http開發(fā)庫Unirest使用及實用技巧
Unirest for Java 是一個輕量級、易于使用的 HTTP 客戶端庫,旨在簡化 Java 應(yīng)用程序中的 HTTP 請求發(fā)送和響應(yīng)處理,本文詳細介紹它的主要特性、基本用法以及一些實用技巧,感興趣的朋友跟隨小編一起看看吧2025-10-10

