`
rabby
  • 浏览: 163419 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

java解压rar文件

阅读更多

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 > -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 > -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在附件中。

分享到:
评论
1 楼 yangqi900 2012-12-04  
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at de.innosystec.unrar.unpack.ppm.SubAllocator.startSubAllocator(SubAllocator.java:157)

没成功,rar中文件数量太多,是不是会出问题

相关推荐

Global site tag (gtag.js) - Google Analytics