Java代码中解压RAR文件
Posted 请叫我码农怪蜀黍
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java代码中解压RAR文件相关的知识,希望对你有一定的参考价值。
- import java.io.File;
- import java.io.FileOutputStream;
- import de.innosystec.unrar.Archive;
- import de.innosystec.unrar.rarfile.FileHeader;
- public class UnRARTools {
- public void unrar(File sourceRar, File destDir) throws Exception {
- Archive archive = null;
- FileOutputStream fos = null;
- System.out.println("Starting...");
- try {
- archive = new Archive(sourceRar);
- FileHeader fh = archive.nextFileHeader();
- int count = 0;
- File destFileName = null;
- while (fh != null) {
- System.out.println((++count) + ") " + fh.getFileNameString());
- String compressFileName = fh.getFileNameString().trim();
- destFileName = new File(destDir.getAbsolutePath() + "/" + compressFileName);
- if (fh.isDirectory()) {
- if (!destFileName.exists()) {
- destFileName.mkdirs();
- }
- fh = archive.nextFileHeader();
- continue;
- }
- if (!destFileName.getParentFile().exists()) {
- destFileName.getParentFile().mkdirs();
- }
- fos = new FileOutputStream(destFileName);
- archive.extractFile(fh, fos);
- fos.close();
- fos = null;
- fh = archive.nextFileHeader();
- }
- archive.close();
- archive = null;
- System.out.println("Finished !");
- } catch (Exception e) {
- throw e;
- } finally {
- if (fos != null) {
- try {
- fos.close();
- fos = null;
- } catch (Exception e) {
- //ignore
- }
- }
- if (archive != null) {
- try {
- archive.close();
- archive = null;
- } catch (Exception e) {
- //ignore
- }
- }
- }
- }
- }
需要引用到以下两个lib.
java-unrar-0.5.jar
http://www.java2s.com/Code/JarDownload/java/java-unrar-0.5.jar.zip
apache-commons-logging.jar
http://www.java2s.com/Code/JarDownload/apache-commons/apache-commons-logging.jar.zip
以上是关于Java代码中解压RAR文件的主要内容,如果未能解决你的问题,请参考以下文章