第一種:
public class fileZipUtil {
/**
* zip文件解壓
* @param inputFile 待解壓文件夾/文件
* @param destDirPath 解壓路徑
*/
public static void unZipFiles(String inputFile,String destDirPath) throws Exception {
File srcFile = new File(inputFile);//獲取當(dāng)前壓縮文件
// 判斷源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));//創(chuàng)建壓縮文件對(duì)象
//開始解壓
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夾,就創(chuàng)建個(gè)文件夾
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
srcFile.mkdirs();
} else {
// 如果是文件,就先創(chuàng)建一個(gè)文件,然后用io流把內(nèi)容copy過去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保證這個(gè)文件的父文件夾必須要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 將壓縮文件內(nèi)容寫入到這個(gè)文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 關(guān)流順序,先打開的后關(guān)閉
fos.close();
is.close();
}
}
}
/**
* 解壓RAR壓縮文件到指定路徑
* @param rarFile RAR壓縮文件
* @param dstDir 解壓到的文件夾路徑
*/
public static void unRarFile(String rarPath, String dstDir) throws Exception {
File dstDiretory = new File(dstDir);
if (!dstDiretory.exists()) {
dstDiretory.mkdirs();
}
try {
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(dstDir + 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(dstDir + 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();
} catch (Exception e) {
throw e;
}
}
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;
}
//使用main方法進(jìn)行測試
public static void main(String[] args) {
try {
String filepath = "E:\\test\\測試1.rar";
String newpath="E:\\test\\zipTest";
//獲取最后一個(gè).的位置
int lastIndexOf = filepath.lastIndexOf(".");
//獲取文件的后綴名 .jpg
String suffix = filepath.substring(lastIndexOf);
System.out.println(suffix);
if(suffix.equals(".zip")){
unZipFiles(filepath,newpath);
}else if(suffix.equals(".rar")){
unRarFile(filepath,newpath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二種:
// 獲取本地rar
public void unRarByPath() {
String rarPath = "D:\\文件.rar";
try {
File outFileDir = new File(rarPath);
Archive archive = new Archive(new FileInputStream(rarFile));
FileHeader fileHeader;
while ((fileHeader = archive.nextFileHeader()) != null) {
// 解決文件名中文亂碼問題
String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() :
fileHeader.getFileNameW();
String fileExt =
fileName.substring(fileName.lastIndexOf(FileConstant.FILE_SEPARATOR) + 1);
System.out.println(fileName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
archive.extractFile(fileHeader, os);
// 將文件信息寫到byte數(shù)組中
byte[] bytes = os.toByteArray();
System.out.println(bytes.length);
if ("rar".equals(fileExt)) {
Archive secondArchive = new Archive(new ByteArrayInputStream(bytes));
// 循環(huán)解壓
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
第三種:
/**
* 根據(jù)原始rar路徑,解壓到指定文件夾下
* 這種方法只能解壓rar 5.0版本以下的,5.0及其以上的無法解決
*
* @param srcRarPath 原始rar路徑+name
* @param dstDirectoryPath 解壓到的文件夾
*/
public static String unRarFile(String srcRarPath, String dstDirectoryPath) throws Exception {
log.debug("unRarFile srcRarPath:{}, dstDirectoryPath:{}", srcRarPath, dstDirectoryPath);
if (!srcRarPath.toLowerCase().endsWith(".rar")) {
log.warn("srcFilePath is not rar file");
return "";
}
File dstDiretory = new File(dstDirectoryPath);
// 目標(biāo)目錄不存在時(shí),創(chuàng)建該文件夾
if (!dstDiretory.exists()) {
dstDiretory.mkdirs();
}
// @Cleanup Archive archive = new Archive(new File(srcRarPath)); com.github.junrar 0.7版本jarAPI
@Cleanup Archive archive = new Archive(new FileInputStream(new File(srcRarPath)));
if (archive != null) {
// 打印文件信息
archive.getMainHeader().print();
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
// 解決中文亂碼問題【壓縮文件中文亂碼】
String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
// 文件夾
if (fileHeader.isDirectory()) {
File fol = new File(dstDirectoryPath + File.separator + fileName.trim());
fol.mkdirs();
} else { // 文件
// 解決linux系統(tǒng)中\(zhòng)分隔符無法識(shí)別問題
String[] fileParts = fileName.split("\\\\");
StringBuilder filePath = new StringBuilder();
for (String filePart : fileParts) {
filePath.append(filePart).append(File.separator);
}
fileName = filePath.substring(0, filePath.length() - 1);
File out = new File(dstDirectoryPath + File.separator + fileName.trim());
if (!out.exists()) {
// 相對(duì)路徑可能多級(jí),可能需要?jiǎng)?chuàng)建父目錄.
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
}
@Cleanup FileOutputStream os = new FileOutputStream(out);
archive.extractFile(fileHeader, os);
}
fileHeader = archive.nextFileHeader();
}
} else {
log.warn("rar file decompression failed , archive is null");
}
return dstDirectoryPath;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-604875.html
文章來源:http://www.zghlxwxcb.cn/news/detail-604875.html
到了這里,關(guān)于Java解壓RAR文件的幾種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!