java解压rar5 兼容rar4

才发现java库没有对rar5压缩算法实现,网上找了一大堆资料,基本都是调用命令的方式,要集成到项目里是很麻烦的,所以一直奔着java解压rar5的目标去找,终于在github上找到了已经实现好的库,希望能帮到大家。

这个库实际是github官方自己实现的,估计是内部项目需要。

按照我下面的步骤就轻松可以完成:

1.pom中添加以下依赖:

<!-- https://mvnrepository.com/artifact/com.github.axet/java-unrar -->
		<dependency>
			<groupId>com.github.axet</groupId>
			<artifactId>java-unrar</artifactId>
			<version>1.7.0-8</version>
		</dependency>
		<dependency>
			<groupId>net.sf.sevenzipjbinding</groupId>
			<artifactId>sevenzipjbinding</artifactId>
			<version>16.02-2.01</version>
		</dependency>
		<dependency>
			<groupId>net.sf.sevenzipjbinding</groupId>
			<artifactId>sevenzipjbinding-all-platforms</artifactId>
			<version>16.02-2.01</version>
		</dependency>

2.java中解压rar5文件的例子:

package rar5;

import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

public class RAR5Test {
	public static void main(String[] args) throws IOException {
		String rarDir = "D:\\keys\\rar5.rar";
		String outDir = "D:\\keys\\rar5";

		RandomAccessFile randomAccessFile = null;
		IInArchive inArchive = null;

		// 第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFile
		randomAccessFile = new RandomAccessFile(rarDir, "r");
		inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));

		int[] in = new int[inArchive.getNumberOfItems()];
		for (int i = 0; i < in.length; i++) {
			in[i] = i;
		}
		inArchive.extract(in, false, new ExtractCallback(inArchive, "366", outDir));

	}
}

3.自己编写回调ExtractCallback

package rar5;

import net.sf.sevenzipjbinding.*;

import java.io.*;

public class ExtractCallback implements IArchiveExtractCallback {

	private int index;
	private String packageName;
	private IInArchive inArchive;
	private String ourDir;

	public ExtractCallback(IInArchive inArchive, String packageName, String ourDir) {
		this.inArchive = inArchive;
		this.packageName = packageName;
		this.ourDir = ourDir;
	}

	@Override
	public void setCompleted(long arg0) throws SevenZipException {
	}

	@Override
	public void setTotal(long arg0) throws SevenZipException {
	}

	@Override
	public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException {
		this.index = index;
		final String path = (String) inArchive.getProperty(index, PropID.PATH);
		final boolean isFolder = (boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
		return new ISequentialOutStream() {
			public int write(byte[] data) throws SevenZipException {
				try {
					if (!isFolder) {
						System.out.println(path);
						File file = new File(ourDir + path);
						save2File(file, data);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return data.length;
			}
		};
	}

	@Override
	public void prepareOperation(ExtractAskMode arg0) throws SevenZipException {
	}

	@Override
	public void setOperationResult(ExtractOperationResult extractOperationResult) throws SevenZipException {
		String path = (String) inArchive.getProperty(index, PropID.PATH);
		boolean isFolder = (boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
//        if(ZipUtils.checkOnlyGetDir(path) && !isFolder){
//            if (extractOperationResult != ExtractOperationResult.OK) {
//                StringBuilder sb = new StringBuilder();
//                sb.append("解压").append(packageName).append("包的").append(path).append("文件");
//                sb.append("失败!");
//                log.error(sb.toString());
//            }
//        }
	}

	public static boolean save2File(File file, byte[] msg) {
		OutputStream fos = null;
		try {
			File parent = file.getParentFile();
			boolean bool;
			if ((!parent.exists()) && (!parent.mkdirs())) {
				return false;
			}
			fos = new FileOutputStream(file);
			fos.write(msg);
			fos.flush();
			return true;
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			File parent;
			return false;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
	}

}

 

好了,就这么简单。

  • 15
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 45
    评论
Java自带的ZipInputStream和ZipOutputStream类只支持解压缩zip格式的文件,不支持rar格式文件的解压缩。要解压rar格式文件,需要使用第三方库。其中,jUnrar是一个比较常用的Java解压rar库,可以实现对rar文件的解压缩。 jUnrar的使用方法如下: 1. 在项目中引入jUnrar库,可以通过Maven或手动下载jar包的方式引入。 2. 使用jUnrar的API进行解压缩操作。下面是一个简单的示例代码: ```java import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.rarfile.FileHeader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class UnRarUtil { /** * 解压缩rar文件 * * @param sourcePath 压缩文件路径 * @param destPath 解压缩目标路径 * @throws IOException * @throws RarException */ public static void unRar(String sourcePath, String destPath) throws IOException, RarException { File srcFile = new File(sourcePath); if (!srcFile.exists()) { throw new RuntimeException("source file not exists!"); } Archive archive = new Archive(new FileVolumeManager(srcFile)); if (archive != null) { archive.getMainHeader().print(); FileHeader fileHeader = archive.nextFileHeader(); while (fileHeader != null) { if (fileHeader.isDirectory()) { File folder = new File(destPath + File.separator + fileHeader.getFileNameString()); folder.mkdirs(); } else { File out = new File(destPath + File.separator + fileHeader.getFileNameString().trim()); FileOutputStream os = new FileOutputStream(out); archive.extractFile(fileHeader, os); os.close(); } fileHeader = archive.nextFileHeader(); } archive.close(); } } } ``` 使用时,只需调用unRar方法,传入要解压的rar文件路径和解压后目标路径即可。
评论 45
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值