admin管理员组文章数量:1632157
方法一
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>
方法二
/**
* 采用命令行方式解压文件
*
* @param rarPath 压缩文件路径
* @param destDir 解压结果路径
* @param cmdPath WinRAR.exe的路径,也可以在代码中写死
* @return
*/
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;
}
// 开始调用命令行解压,参数-o+是表示覆盖的意思
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;
}
版权声明:本文标题:Java 解压rar文件的两种方法 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729114138a1187115.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论