方法一
private static void extractRar(String rarPath, String destDir) throws IOException, RarException {
File dstDiretory = new File(destDir);
if (!dstDiretory.exists()) {
dstDiretory.mkdirs();
}
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(destDir + 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(destDir + 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();
}
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;
}
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
方法二
public static boolean realExtract(String rarPath, String destDir, String cmdPath) {
File rarFile = new File(rarPath);
destDir = new File(destDir).getAbsoluteFile().getAbsolutePath();
while (destDir.contains("..")) {
String[] sepList = destDir.split("\\\\");
destDir = "";
for (int i = 0; i < sepList.length; i++) {
if (!"..".equals(sepList[i]) && i < sepList.length - 1 && "..".equals(sepList[i + 1])) {
i++;
} else {
destDir += sepList[i] + File.separator;
}
}
}
boolean bool = false;
if (!rarFile.exists()) {
return false;
}
String cmd = cmdPath + " X -o+ " + rarFile + " " + destDir;
System.out.println(cmd);
try {
Process proc = Runtime.getRuntime().exec(cmd);
if (proc.waitFor() != 0) {
if (proc.exitValue() == 0) {
bool = false;
}
} else {
bool = true;
}
} catch (Exception e) {
e.printStackTrace();
}
rarFile.delete();
return bool;
}