Java解壓RAR文件的三種方式
第一種:
public class fileZipUtil {
/**
* zip文件解壓
* @param inputFile 待解壓文件夾/文件
* @param destDirPath 解壓路徑
*/
public static void unZipFiles(String inputFile,String destDirPath) throws Exception {
File srcFile = new File(inputFile);//獲取當(dāng)前壓縮文件
// 判斷源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));//創(chuàng)建壓縮文件對(duì)象
//開始解壓
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夾,就創(chuàng)建個(gè)文件夾
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
srcFile.mkdirs();
} else {
// 如果是文件,就先創(chuàng)建一個(gè)文件,然后用io流把內(nèi)容copy過去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保證這個(gè)文件的父文件夾必須要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 將壓縮文件內(nèi)容寫入到這個(gè)文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 關(guān)流順序,先打開的后關(guān)閉
fos.close();
is.close();
}
}
}
/**
* 解壓RAR壓縮文件到指定路徑
* @param rarFile RAR壓縮文件
* @param dstDir 解壓到的文件夾路徑
*/
public static void unRarFile(String rarPath, String dstDir) throws Exception {
File dstDiretory = new File(dstDir);
if (!dstDiretory.exists()) {
dstDiretory.mkdirs();
}
try {
File rarFile= new File(rarPath);
Archive archive = new Archive(new FileInputStream(rarFile));
List<FileHeader> fileHeaders = archive.getFileHeaders();
for (FileHeader fileHeader : fileHeaders) {
if (fileHeader.isDirectory()) {
String fileName= fileHeader.getFileNameW();
if(!existZH(fileName)){
fileName = fileHeader.getFileNameString();
}
File dir = new File(dstDir + File.separator + fileName);
if (!dir.exists()){
dir.mkdirs();
}
} else {
String fileName= fileHeader.getFileNameW().trim();
if(!existZH(fileName)){
fileName = fileHeader.getFileNameString().trim();
}
File file = new File(dstDir + File.separator + fileName);
try {
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
FileOutputStream os = new FileOutputStream(file);
archive.extractFile(fileHeader, os);
os.close();
} catch (Exception ex) {
throw ex;
}
}
}
archive.close();
} catch (Exception e) {
throw e;
}
}
public static boolean existZH(String str) {
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
return true;
}
return false;
}
//使用main方法進(jìn)行測試
public static void main(String[] args) {
try {
String filepath = "E:\\test\\測試1.rar";
String newpath="E:\\test\\zipTest";
//獲取最后一個(gè).的位置
int lastIndexOf = filepath.lastIndexOf(".");
//獲取文件的后綴名 .jpg
String suffix = filepath.substring(lastIndexOf);
System.out.println(suffix);
if(suffix.equals(".zip")){
unZipFiles(filepath,newpath);
}else if(suffix.equals(".rar")){
unRarFile(filepath,newpath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}第二種:
// 獲取本地rar
public void unRarByPath() {
String rarPath = "D:\\文件.rar";
try {
File outFileDir = new File(rarPath);
Archive archive = new Archive(new FileInputStream(rarFile));
FileHeader fileHeader;
while ((fileHeader = archive.nextFileHeader()) != null) {
// 解決文件名中文亂碼問題
String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() :
fileHeader.getFileNameW();
String fileExt =
fileName.substring(fileName.lastIndexOf(FileConstant.FILE_SEPARATOR) + 1);
System.out.println(fileName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
archive.extractFile(fileHeader, os);
// 將文件信息寫到byte數(shù)組中
byte[] bytes = os.toByteArray();
System.out.println(bytes.length);
if ("rar".equals(fileExt)) {
Archive secondArchive = new Archive(new ByteArrayInputStream(bytes));
// 循環(huán)解壓
}
}
} catch (IOException e) {
e.printStackTrace();
}
}第三種:
/**
* 根據(jù)原始rar路徑,解壓到指定文件夾下
* 這種方法只能解壓rar 5.0版本以下的,5.0及其以上的無法解決
*
* @param srcRarPath 原始rar路徑+name
* @param dstDirectoryPath 解壓到的文件夾
*/
public static String unRarFile(String srcRarPath, String dstDirectoryPath) throws Exception {
log.debug("unRarFile srcRarPath:{}, dstDirectoryPath:{}", srcRarPath, dstDirectoryPath);
if (!srcRarPath.toLowerCase().endsWith(".rar")) {
log.warn("srcFilePath is not rar file");
return "";
}
File dstDiretory = new File(dstDirectoryPath);
// 目標(biāo)目錄不存在時(shí),創(chuàng)建該文件夾
if (!dstDiretory.exists()) {
dstDiretory.mkdirs();
}
// @Cleanup Archive archive = new Archive(new File(srcRarPath)); com.github.junrar 0.7版本jarAPI
@Cleanup Archive archive = new Archive(new FileInputStream(new File(srcRarPath)));
if (archive != null) {
// 打印文件信息
archive.getMainHeader().print();
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
// 解決中文亂碼問題【壓縮文件中文亂碼】
String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
// 文件夾
if (fileHeader.isDirectory()) {
File fol = new File(dstDirectoryPath + File.separator + fileName.trim());
fol.mkdirs();
} else { // 文件
// 解決linux系統(tǒng)中\(zhòng)分隔符無法識(shí)別問題
String[] fileParts = fileName.split("\\\\");
StringBuilder filePath = new StringBuilder();
for (String filePart : fileParts) {
filePath.append(filePart).append(File.separator);
}
fileName = filePath.substring(0, filePath.length() - 1);
File out = new File(dstDirectoryPath + File.separator + fileName.trim());
if (!out.exists()) {
// 相對(duì)路徑可能多級(jí),可能需要?jiǎng)?chuàng)建父目錄.
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
}
@Cleanup FileOutputStream os = new FileOutputStream(out);
archive.extractFile(fileHeader, os);
}
fileHeader = archive.nextFileHeader();
}
} else {
log.warn("rar file decompression failed , archive is null");
}
return dstDirectoryPath;
}總結(jié)
到此這篇關(guān)于Java解壓RAR文件的三種方式的文章就介紹到這了,更多相關(guān)Java解壓RAR文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JDBC+GUI實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了JDBC+GUI實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
JSP 開發(fā)之 releaseSession的實(shí)例詳解
這篇文章主要介紹了JSP 開發(fā)之 releaseSession的實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-07-07
關(guān)于Spring中@Value注解使用和源碼分析
通過深入分析@Value注解的使用和源碼,本文詳細(xì)解釋了Spring如何解析@Value注解并為屬性賦值,首先,Spring會(huì)解析并收集所有被@Value注解修飾的屬性,這一過程依賴于AutowiredAnnotationBeanPostProcessor類2024-11-11
SpringBoot對(duì)接clerk實(shí)現(xiàn)用戶信息獲取功能
Clerk是一個(gè)提供身份驗(yàn)證和用戶管理的服務(wù),可以幫助開發(fā)者快速集成這些功能,下面我們就來看看如何使用Spring?Boot對(duì)接Clerk實(shí)現(xiàn)用戶信息的獲取吧2025-02-02
SpringBoot2.0實(shí)現(xiàn)多圖片上傳加回顯
這兩天公司有需求讓做一個(gè)商戶注冊的后臺(tái)功能,其中需要商戶上傳多張圖片并回顯,本文就使用SpringBoot2.0實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2021-07-07
java開發(fā)中如何使用JVisualVM進(jìn)行性能分析
JVisualVM是由Sun提供的性能分析工具,如此強(qiáng)大的后盾怎能不強(qiáng)大?在Jdk6.0以后的版本中是自帶的,配置好環(huán)境變量然后在運(yùn)行中輸入“JVisualVm”或直接到Jdk的安裝目錄的Bin目錄下找到運(yùn)行程序即可運(yùn)行。如果是用Jdk1.5或以前版本的朋友就得要單獨(dú)安裝了2015-12-12
Spring?BeanDefinition父子關(guān)系示例解析
這篇文章主要為大家介紹了Spring?BeanDefinition父子關(guān)系示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
java.net.UnknownHostException異常的一般原因及解決步驟
關(guān)于java.net.UnknownHostException大家也許都比較熟悉,這篇文章主要給大家介紹了關(guān)于java.net.UnknownHostException異常的一般原因及解決步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02

