Java解压带密码的Rar压缩文件

16 篇文章 0 订阅
5 篇文章 0 订阅

RAR压缩算法是不公开的,所以这方面的开源项目不多

幸好有一个叫unrar的开源项目支持RAR的解压,但不能压缩RAR文件

不过,直接使用unrar却不能支持带密码的RAR文件解压,经过多方查找,终于在Google Code上面找到一个支持密码的unrar版本,下载地址:http://code.google.com/p/java-unrar/ 

该项目依赖Jar包:

commons-logging.jar  比较常用,可以到Apache官网下载

gnu-crypto.jar   可以在http://www.gnu.org/software/gnu-crypto/下载

下面是一个简单的解压示例:

package com.ninemax.demo.rar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;

/**
 * RAR格式压缩文件解压工具类
 * 不支持RAR格式压缩
 * 支持中文,支持RAR压缩文件密码
 * 依赖jar包
 * commons-io.jar
 * commons-logging.jar
 * java-unrar-decryption-supported.jar
 * gnu-crypto.jar
 * 
 * @author ninemax
 */
public class RarDecompressionUtil {
	
	public static final String SEPARATOR = File.separator;
	
	// =============================== RAR Format ================================
	/**
	 * 解压指定RAR文件到当前文件夹
	 * @param srcRar 指定解压
	 *  @param password 压缩文件时设定的密码
	 * @throws IOException 
	 */
	public static void unrar(String srcRar, String password) throws IOException {
		unrar(srcRar, null, password);
	}
	
	/**
	 * 解压指定的RAR压缩文件到指定的目录中
	 * @param srcRar 指定的RAR压缩文件
	 * @param destPath 指定解压到的目录
	 *  @param password 压缩文件时设定的密码
	 * @throws IOException 
	 */
	public static void unrar(String srcRar, String destPath, String password) throws IOException {
		File srcFile = new File(srcRar);
		if (!srcFile.exists()) {
			return;
		}
		if (null == destPath || destPath.length() == 0) {
			unrar(srcFile, srcFile.getParent(), password);
			return;
		}
		unrar(srcFile,destPath, password);
	}
	
	/**
	 * 解压指定RAR文件到当前文件夹
	 * @param srcRarFile 解压文件
	 *  @param password 压缩文件时设定的密码
	 * @throws IOException 
	 */
	public static void unrar(File srcRarFile, String password) throws IOException {
		if (null == srcRarFile || !srcRarFile.exists()) {
			throw new IOException("指定文件不存在.");
		}
		unrar(srcRarFile, srcRarFile.getParent(),password);
	}
	
	/**
	 * 解压指定RAR文件到指定的路径
	 * @param srcRarFile 需要解压RAR文件
	 * @param destPath 指定解压路径
	 * @param password 压缩文件时设定的密码
	 * @throws IOException 
	 */
	public static void unrar(File srcRarFile, String destPath, String password) throws IOException {
		if (null == srcRarFile || !srcRarFile.exists()) {
			throw new IOException("指定压缩文件不存在.");
		}
		if (!destPath.endsWith(SEPARATOR)) {
			destPath += SEPARATOR;
		}
		Archive archive = null;
		OutputStream unOut = null;
		try {
			archive = new Archive(srcRarFile, password, false);
			FileHeader fileHeader = archive.nextFileHeader();
			while(null != fileHeader) {
				if (!fileHeader.isDirectory()) {
					// 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
					String destFileName = "";
					String destDirName = "";
					if (SEPARATOR.equals("/")) {		// 非windows系统
						destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("\\\\", "/");
						destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
					} else {		// windows系统
						destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("/", "\\\\");
						destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
					}
					// 2创建文件夹
					File dir = new File(destDirName);
					if (!dir.exists() || !dir.isDirectory()) {
						dir.mkdirs();
					}
					// 抽取压缩文件
					unOut = new FileOutputStream(new File(destFileName));
					archive.extractFile(fileHeader, unOut);
					unOut.flush();
					unOut.close();
				}
				fileHeader = archive.nextFileHeader();
			}
			archive.close();
		} catch (RarException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(unOut);
		}
	}
}

相关资源下载地址:

http://code.google.com/p/java-unrar/downloads/list

或者

http://download.csdn.net/detail/zhangyihui1986/4415967

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
压缩文件方法 该方法需要引用zip4j的jar文件 单个文件、多个文件压缩 /** * 使用给定密码压缩指定文件或文件夹到指定位置. * * dest可传最终压缩文件存放的绝对路径,也可以传存放目录,也可以传null或者"". * 如果传null或者""则将压缩文件存放在当前目录,即跟源文件同目录,压缩文件名取源文件名,以.zip为后缀; * 如果以路径分隔符(File.separator)结尾,则视为目录,压缩文件名取源文件名,以.zip为后缀,否则视为文件名. * @param src 要压缩的文件或文件夹路径 * @param dest 压缩文件存放路径 * @param isCreateDir 是否在压缩文件里创建目录,仅在压缩文件为目录时有效. * 如果为false,将直接压缩目录下文件到压缩文件. * @param passwd 压缩使用的密码 * @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败. */ 方法详细见文件! 可选择文件list压缩 /** * 使用给定密码压缩指定文件list * dest可传最终压缩文件存放的绝对路径,也可以传存放目录,也可以传null或者"". * 如果传null或者""则将压缩文件存放在当前目录,即跟源文件同目录,压缩文件名取源文件名,以.zip为后缀; * 如果以路径分隔符(File.separator)结尾,则视为目录,压缩文件名取源文件名,以.zip为后缀,否则视为文件名. * @param src 要压缩的文件集合 * @param dest 压缩文件存放路径 * @param isCreateDir 是否在压缩文件里创建目录,仅在压缩文件为目录时有效. * 如果为false,将直接压缩目录下文件到压缩文件. * @param passwd 压缩使用的密码 * @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败. */ 方法详细见文件! 解压 /** * 使用给定密码解压指定的ZIP压缩文件到指定目录 * * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出 * @param zipFile 指定的ZIP压缩文件 * @param dest 解压目录 * @param passwd ZIP文件的密码 * @return 解压后文件数组 * @throws ZipException 压缩文件有损坏或者解压缩失败抛出 */ 方法详细见文件! 一个简单的demo 欢迎大家指点,一起提升
### 回答1: 要解压RAR5文件,可以使用Java的第三方库,如Apache Commons Compress或SevenZipJBinding。下面是使用Apache Commons Compress库解压RAR5文件的示例代码: ``` import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.sevenz.SevenZFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Rar5Extractor { public static void main(String[] args) { File rarFile = new File("path/to/rarFile.rar"); // 替换为RAR5文件的路径 try (ArchiveInputStream ais = new SevenZFile(rarFile)) { ArchiveEntry entry; while ((entry = ais.getNextEntry()) != null) { if (!entry.isDirectory()) { String entryName = entry.getName(); byte[] content = new byte[(int) entry.getSize()]; int bytesRead = ais.read(content); if (bytesRead == -1) { throw new IOException("Error reading entry: " + entryName); } File outputFile = new File("path/to/output/" + entryName); // 替换为输出文件的路径 try (FileOutputStream fos = new FileOutputStream(outputFile)) { fos.write(content); } } } } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码使用Apache Commons Compress库中的SevenZFile类来解压RAR5文件。遍历压缩文件中的每个条目,如果是文件而不是目录,则读取条目的内容,并将其写入到输出文件中。请将代码中的路径根据实际情况进行替换。 请注意,要使用Apache Commons Compress库,需要将其添加为项目的依赖。可以通过Maven或Gradle将以下依赖项添加到项目中的`pom.xml`或`build.gradle`文件中: Maven: ``` <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> </dependency> </dependencies> ``` Gradle: ``` dependencies { implementation 'org.apache.commons:commons-compress:1.21' } ``` 这样,您就可以使用Java解压RAR5文件了。 ### 回答2: 要在Java解压RAR5文件,可以借助第三方开源库进行操作,比如使用commons-compress库。以下是使用该库实现解压RAR5文件的示例代码: 首先,需要在项目中引入commons-compress库的依赖,比如在Maven项目中的pom.xml文件中添加以下代码: ``` <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> </dependency> </dependencies> ``` 然后,在Java代码中使用以下代码实现解压RAR5文件: ``` import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.rar.RarArchiveInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class RarExtractor { public static void main(String[] args) { String rarFilePath = "path/to/rar/file.rar"; String extractDir = "path/to/extract/directory/"; try (ArchiveInputStream inputStream = new RarArchiveInputStream(new FileInputStream(rarFilePath))) { ArchiveEntry entry = inputStream.getNextEntry(); while (entry != null) { String entryName = entry.getName(); String entryPath = extractDir + entryName; if (entry.isDirectory()) { new File(entryPath).mkdirs(); } else { byte[] buffer = new byte[8192]; int bytesRead; try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(entryPath))) { while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } entry = inputStream.getNextEntry(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 通过上述代码,可以将RAR5文件解压到指定目录下。其中,`rarFilePath`为待解压RAR5文件路径,`extractDir`为解压后的文件存放目录路径。请确保Java环境中已经安装并配置好commons-compress库。 ### 回答3: 要使用Java解压RAR5文件,可以使用第三方库raroscope或ra-rcp来实现。 1.使用raroscope解压RAR5文件: Raroscope是一个开源的Java库,用于处理RAR格式的文件。以下是使用raroscope解压RAR5文件的步骤: 首先,下载并导入raroscope库到您的项目中。 在Java代码中,使用Raroscope提供的解压功能。您可以指定RAR5文件的路径和解压目标路径,并调用解压方法。 示例代码如下: ``` import org.gagravarr.rar.RarArchive; import org.gagravarr.rar.RarEntry; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class RAR5Extractor { public static void main(String[] args) { File rarFile = new File("path/to/rar5/file.rar"); File destDir = new File("path/to/extract/destination"); try { RarArchive archive = new RarArchive(rarFile); for (RarEntry entry : archive.getEntries()) { if (!entry.isDirectory()) { File outputFile = new File(destDir, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] content = new byte[(int) entry.getSize()]; archive.read(entry, content); outputStream.write(content); outputStream.close(); } } archive.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2.使用ra-rcp解压RAR5文件: ra-rcp是RAR解压缩工具的Java API。以下是使用ra-rcp解压RAR5文件的步骤: 首先,下载并导入ra-rcp库到您的项目中。 在Java代码中,使用ra-rcp提供的解压功能。通过设置RarOptions中的isOldStyleRar属性为false,可以解压RAR5格式的文件。 示例代码如下: ``` import com.rarchive.ra.RA; import com.rarchive.ra.RarFile; import com.rarchive.rar.options.RarOptions; import java.io.File; import java.nio.file.Path; public class RAR5Extractor { public static void main(String[] args) { Path rarFile = new File("path/to/rar5/file.rar").toPath(); Path destDir = new File("path/to/extract/destination").toPath(); try (RA ra = new RA()) { RarOptions options = new RarOptions(); options.setIgnorePath(true); options.setOverwriteMode(RarOptions.OverwriteMode.OVERWRITE); options.setOldStyleRar(false); ra.open(rarFile.toString()); ra.listEntries(); ra.extractAll(destDir.toString(), options); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上是使用Java解压RAR5文件的两种方法,您可以根据自己的需求选择合适的方法进行处理。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值