上传者: tuposky
|
上传时间: 2021-11-29 17:24:28
|
文件大小: 130KB
|
文件类型: -
java 解压rar的依赖jar包。不需要安装winrar。支持windows和linux
附上代码。
/**
* 解压rar格式压缩包
* 依赖包:java-unrar-0.3.jar,commons-logging-1.1.1.jar
* @param sourceRar
* @param destDir
* @throws Exception
*/
private static void unrar(String sourceRar, String destDir)
throws Exception {
Archive archive = null;
FileOutputStream fos = null;
try {
archive = new Archive(new File(sourceRar));
FileHeader fh = archive.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
//根据不同的操作系统拿到相应的 destDirName 和 destFileName
String compressFileName = fh.getFileNameString().trim();
String destFileName = "";
String destDirName = "";
//非windows系统
if (File.separator.equals("/")) {
destFileName = destDir
+ compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0,
destFileName.lastIndexOf("/"));
//windows系统
} else {
destFileName = destDir
+ compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0,
destFileName.lastIndexOf("\\"));
}
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
//解压文件
fos = new FileOutputStream(new File(destFileName));
archive.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = archive.nextFileHeader();
}
archive.close();
} catch (Exception e) {
throw e;
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (archive != null) {
try {
archive.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}