---
title: "java解压rar文件"
author: "rabby"
date: "2012-04-12T01:21:32Z"
tags: []
categories: ["移动开发"]
slug: "java-rar"
draft: false
lastmod: "2012-04-12T01:21:32Z"
id: 1484020
url: "https://rabby.iteye.com/blog/1484020"
---

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;

import de.innosystec.unrar.Archive;  
import de.innosystec.unrar.rarfile.FileHeader;

public class Decompress {

public static boolean existZH(String str) {  
String regEx = "\[\\\\u4e00-\\\\u9fa5]";  
Pattern p = Pattern.compile(regEx);  
Matcher m = p.matcher(str);  
return m.find();  
}

public static String getFileName(String fileName){  
if (null == fileName && "".equals(fileName)) {  
return "";  
}  
int index = fileName.lastIndexOf(".");  
return fileName.substring(0, index);  
}

public static boolean unrarFile(String rarFilePath, String extPlace){  
boolean flag = false;  
if (null == rarFilePath || "".equals(rarFilePath.trim())) {  
System.out.println("rar文件路径为空.");  
return flag;  
} else {  
int index = rarFilePath.lastIndexOf(".");  
if (index &gt; -1) {  
String suffix = rarFilePath.substring(index + 1, rarFilePath.length());  
if (!"rar".equalsIgnoreCase(suffix)) {  
System.out.println("压缩文件格式不正确.");  
return flag;  
}  
}  
}  
if (null == extPlace || "".equals(extPlace.trim())) {  
System.out.println("解压路径为空.");  
return flag;  
}

Archive archive = null;  
OutputStream os = null;

try {  
File file = new File(rarFilePath);  
String extDir = extPlace + getFileName(file.getName()) + File.separator;  
archive = new Archive(file);  
FileHeader fh = archive.nextFileHeader();

String fileName = null;  
String path = null;  
String dirPath = null;  
File dir = null;  
while (null != fh) {  
fileName = fh.getFileNameW().trim();  
if (!existZH(fileName)) {  
fileName = fh.getFileNameString();  
}

path = (extDir + fileName).replaceAll("[\\\\\\\\]()", "/");  
int end = path.lastIndexOf("/");  
if (end &gt; -1) {  
dirPath = path.substring(0, end);  
}

dir = new File(dirPath);  
if (!dir.exists()) {  
dir.mkdirs();  
}

if (fh.isDirectory()) {  
fh = archive.nextFileHeader();  
continue;  
}

os = new FileOutputStream(extDir + fileName);  
archive.extractFile(fh, os);  
os.flush();  
os.close();

fh = archive.nextFileHeader();  
}  
flag = true;  
} catch (Exception e) {  
e.printStackTrace();  
} finally {  
if (null != os) {  
try {  
os.flush();  
os.close();  
} catch (IOException e) {  
e.printStackTrace();  
}  
}  
if (null != archive) {  
try {  
archive.close();  
} catch (IOException e) {  
e.printStackTrace();  
}  
}  
}

return flag;  
}  
}

 

 

java-unrar-0.3.jar在附件中。