JAVA解压rar文件的三种方式

第一种:

public class fileZipUtil {
	/**
	 * zip文件解压
	 * @param inputFile  待解压文件夹/文件
	 * @param destDirPath  解压路径
	 */
	public static void unZipFiles(String inputFile,String destDirPath) throws Exception {
		File srcFile = new File(inputFile);//获取当前压缩文件
		// 判断源文件是否存在
		if (!srcFile.exists()) {
			throw new Exception(srcFile.getPath() + "所指文件不存在");
		}
		ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));//创建压缩文件对象
		//开始解压
		Enumeration<?> entries = zipFile.entries();
		while (entries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			// 如果是文件夹,就创建个文件夹
			if (entry.isDirectory()) {
				String dirPath = destDirPath + "/" + entry.getName();
				srcFile.mkdirs();
			} else {
				// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
				File targetFile = new File(destDirPath + "/" + entry.getName());
				// 保证这个文件的父文件夹必须要存在
				if (!targetFile.getParentFile().exists()) {
					targetFile.getParentFile().mkdirs();
				}
				targetFile.createNewFile();
				// 将压缩文件内容写入到这个文件中
				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);
				}
				// 关流顺序,先打开的后关闭
				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方法进行测试
	public static void main(String[] args) {
		try {
			String filepath = "E:\\test\\测试1.rar";
			String newpath="E:\\test\\zipTest";
			//获取最后一个.的位置
			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数组中
             byte[] bytes = os.toByteArray();
             System.out.println(bytes.length);
             if ("rar".equals(fileExt)) {
                 Archive secondArchive = new Archive(new ByteArrayInputStream(bytes));
                 // 循环解压
             }
         }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 第三种:

/**
     * 根据原始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);
        // 目标目录不存在时,创建该文件夹
        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系统中\分隔符无法识别问题
                    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()) {
                        // 相对路径可能多级,可能需要创建父目录.
                        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;
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java自身并不支持解压RAR文件,需要使用第三方库来实现。 我推荐使用Junrar这个库来解压RAR文件,它是一个开源库,可以在Github上找到它的代码和文档。 以下是一个简单的示例代码,演示如何使用Junrar库来解压RAR文件: ```java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.rarfile.FileHeader; public class RarExtractor { public static void extract(String filePath, String outputFolder) throws IOException, RarException { Archive archive = null; try { archive = new Archive(new FileVolumeManager(new File(filePath))); if (archive != null) { archive.getMainHeader().print(); List<FileHeader> headers = archive.getFileHeaders(); for (FileHeader header : headers) { if (header.isDirectory()) { continue; } File file = new File(outputFolder + File.separator + header.getFileNameString().trim()); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } OutputStream os = null; try { os = new FileOutputStream(file); archive.extractFile(header, os); } finally { if (os != null) { os.close(); } } } } } finally { if (archive != null) { archive.close(); } } } public static void main(String[] args) { String filePath = "path/to/rar/file.rar"; String outputFolder = "output/folder/path"; try { extract(filePath, outputFolder); } catch (IOException e) { e.printStackTrace(); } catch (RarException e) { e.printStackTrace(); } } } ``` 你需要将上述代码中的 `filePath` 和 `outputFolder` 替换成你自己的RAR文件路径和输出目录路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DN金猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值