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;
    }

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java可以使用Apache Commons Compress库来解压RAR压缩包和嵌套的GZ压缩包。以下是一个示例代码: ```java import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import java.io.*; public class Unpacker { public static void main(String[] args) throws IOException, ArchiveException { String rarFilePath = "path/to/rar/file.rar"; String outputDirPath = "path/to/output/dir"; // 创建RAR文件输入流 FileInputStream rarFileInputStream = new FileInputStream(rarFilePath); ArchiveInputStream rarArchiveInputStream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.RAR, rarFileInputStream); // 遍历RAR文件中的所有文件 ArchiveEntry rarEntry; while ((rarEntry = rarArchiveInputStream.getNextEntry()) != null) { String entryName = rarEntry.getName(); long entrySize = rarEntry.getSize(); // 如果是GZ文件,则继续解压 if (entryName.endsWith(".gz")) { // 创建GZ文件输入流 InputStream gzInputStream = new BufferedInputStream(rarArchiveInputStream); CompressorInputStream gzCompressorInputStream = new CompressorStreamFactory().createCompressorInputStream(CompressorStreamFactory.GZIP, gzInputStream); // 创建输出流,将解压后的文件写入输出流 String outputFilePath = outputDirPath + File.separator + entryName.substring(0, entryName.length() - 3); FileOutputStream outputStream = new FileOutputStream(outputFilePath); byte[] buffer = new byte[1024]; int n; while ((n = gzCompressorInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, n); } // 关闭输出流和GZ文件输入流 outputStream.close(); gzCompressorInputStream.close(); } } // 关闭RAR文件输入流 rarArchiveInputStream.close(); rarFileInputStream.close(); } } ``` 在上面的示例代码中,我们首先创建一个RAR文件输入流,然后使用Apache Commons Compress库的`ArchiveStreamFactory.createArchiveInputStream()`方法创建一个RAR文件归档输入流。接下来,我们遍历RAR文件中的所有文件,如果发现一个GZ文件,就创建一个GZ文件输入流,使用Apache Commons Compress库的`CompressorStreamFactory.createCompressorInputStream()`方法创建一个GZ文件压缩输入流。然后,我们创建一个输出流,将解压后的文件写入输出流。最后,我们关闭所有的输入流和输出流。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值